Javacript数据转换问题

时间:2019-04-25 04:54:18

标签: javascript xmlhttprequest

在javascript中要根据我的要求进行数据处理,但我不知道如何转换数据。我从Fitbit获取数据,并且Web api响应提供json数据,我想使用javascript更改该数据。 我的Api回复显示在下面。

0: {date: "2019-4-25"}
1: {distance: "1.0627499999999999"}
2: {minutes: "30"}
3: {calories: "19"}
4: {steps: "750"}

我想获得喜欢的数据:-

 "2019-04-25":{distance: "0.7085",steps: "500"minutes: "20",calories: "187"}

下面显示了我的JavaScript代码,请帮助我如何根据数据明智的方法来获取对象内部的数据...

app.js

let date = new Date();
let todayDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
//  let endDate =`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate() + 1}`;
//   console.log(endDate);
var url = window.location.href;

//getting the access token from url
var access_token = url.split("#")[1].split("=")[1].split("&")[0];

// get the userid
var userId = url.split("#")[1].split("=")[2].split("&")[0];

// console.log(access_token);

var response = [];
var key = "date";
var obj = {};
obj[key] = todayDate;
response.push(obj);
console.log(response);
// Make an API request and graph it
var processResponse = function (res) {
    if (!res.ok) {
        throw new Error('Fitbit API request failed: ' + res);
    }

    var contentType = res.headers.get('content-type')
    if (contentType && contentType.indexOf("application/json") !== -1) {
        return res.json();
    } else {
        throw new Error('JSON expected but received ' + contentType);
    }
}
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.fitbit.com/1/user/' + userId + '/activities/steps/date/today/1d.json');
xhr.setRequestHeader("Authorization", 'Bearer ' + access_token);
xhr.onload = function () {
    if (xhr.status === 200) {

        var d1 = xhr.responseText;
        var jsonResponse = JSON.parse(d1);
        var steps = jsonResponse["activities-steps"][0].value;
        console.log("steps:", steps);
        var key = "steps";
        var obj = {};
        obj[key] = steps;
        response.push(obj);

    }
};
xhr.send();
var xhr2 = new XMLHttpRequest();
xhr2.open('GET', 'https://api.fitbit.com/1/user/' + userId + '/activities/distance/date/today/1d.json');
xhr2.setRequestHeader("Authorization", 'Bearer ' + access_token);
xhr2.onload = function () {
    if (xhr2.status === 200) {
        var d2 = xhr2.responseText;
        var jsonResponse = JSON.parse(d2);
        var distance = jsonResponse["activities-distance"][0].value;
        var key = "distance";
        var obj = {};
        obj[key] = distance;
        response.push(obj);
        console.log("distance:", distance);


    }
};
xhr2.send();

var xhr3 = new XMLHttpRequest();
xhr3.open('GET', 'https://api.fitbit.com/1/user/' + userId + '/activities/activityCalories/date/today/1d.json');
xhr3.setRequestHeader("Authorization", 'Bearer ' + access_token);
xhr3.onload = function () {
    if (xhr3.status === 200) {
        var d3 = xhr3.responseText;
        var jsonResponse = JSON.parse(d3);
        var calories = jsonResponse["activities-activityCalories"][0].value;
        var key = "calories";
        var obj = {};
        obj[key] = calories;
        response.push(obj);

        console.log("calories:", calories);
        //document.write(xhr2.responseText);
    }
};
xhr3.send();

var xhr4 = new XMLHttpRequest();
xhr4.open('GET', 'https://api.fitbit.com/1/user/' + userId + '/activities/minutesVeryActive/date/today/1d.json');
xhr4.setRequestHeader("Authorization", 'Bearer ' + access_token);
xhr4.onload = function () {
    if (xhr4.status === 200) {
        var d4 = xhr4.responseText;
        var jsonResponse = JSON.parse(d4);
        var minutes = jsonResponse["activities-minutesVeryActive"][0].value;
        var key = "minutes";
        var obj = {};
        obj[key] = minutes;
        response.push(obj);

        console.log("minutes:", minutes);

    }
};

xhr4.send();

3 个答案:

答案 0 :(得分:1)

我为您编码;) 您最多可以通过以下方式将响应转换为新对象:

const res = {
  0: {date: "2019-4-25"},
  1: {distance: "1.0627499999999999"},
  2: {minutes: "30"},
  3: {calories: "19"},
  4: {steps: "750"},
}

const resconverted = {
  [res[0].date] : {
   'distance':res[1].distance,
   'minutes':res[2].minutes,
   'calories':res[3].calories,
   'steps':res[4].steps
 }
}


console.log(res);
console.log(resconverted);

答案 1 :(得分:0)

您显示的第一段代码是应该起作用的数组还是对象:

var obj = {
  '0': {date: "2019-4-25"},
  '1': {distance: "1.0627499999999999"},
  '2': {minutes: "30"},
  '3': {calories: "19"},
  '4': {steps: "750"}
};
var res = {};
res[obj[0].date] = {
  distance:obj[1].distance,
  steps:obj[4].steps,
  minutes:obj[2].minutes,
  calories:obj[3].calories
};
console.log(res);
var array = [
  {date: "2019-4-25"},
  {distance: "1.0627499999999999"},
  {minutes: "30"},
  {calories: "19"},
  {steps: "750"}
];
var res2 = {};
res2[array[0].date] = {
  distance:array[1].distance,
  steps:array[4].steps,
  minutes:array[2].minutes,
  calories:array[3].calories
}
console.log(res2);

您当然应该知道对象属性的顺序取决于浏览器。

答案 2 :(得分:0)

使用它并动态转换响应:

const res = {
  0: {date: "2019-4-25"},
  1: {distance: "1.0627499999999999"},
  2: {minutes: "30"},
  3: {calories: "19"},
  4: {steps: "750"},
}

let k =[];
let v =[]
Object.getOwnPropertyNames(res).map((key)=>{  
  p =Object.getOwnPropertyNames(res[key]).map((key1,index)=>{  
    k.push(key1);
    v.push(res[key][key1]);
  })
})

let o = {} ;
for(i=0; i<k.length;i++)
{
 o[k[i]] = v[i];
}

console.log(o);

这是肮脏的代码,请清理它;)