我有一个json对象和一个虚拟json响应。 我需要遍历它,并获得每个坐标的新数组,每个循环一个。
示例JSON:
customersBarChart: {
"2014": {
"x": 1,
"y": 5,
"z":10
},
"2015": {
"x": 8,
"y": 2,
"z":5
},
}
预期结果是:
first X loop MyArray = [1,8]
second Y loop MyArray = [5,2]
third Z loop MyArray = [10,5]
答案 0 :(得分:0)
您可以使用for (let o in obj)
遍历对象并从那里获取值。现在,您可以通过将obj[o]
中的数据推入指定数组的末尾来制作3个单独的数组。
let obj = {
"2014": {
"x": 1,
"y": 5,
"z": 10
},
"2015": {
"x": 8,
"y": 2,
"z": 5
},
}
let arr1 = []
let arr2 = []
let arr3 = []
for (let o in obj) {
arr1.push(obj[o].x)
arr2.push(obj[o].y)
arr3.push(obj[o].z)
}
console.log(arr1.join())
console.log(arr2.join())
console.log(arr3.join())
答案 1 :(得分:0)
这是动态处理事情的方法。
var oData = {
customersBarChart: {
"2014": {
"x": 1,
"y": 5,
"z": 10
},
"2015": {
"x": 8,
"y": 2,
"z": 5
},
}
}
function extractData(data) {
// get the keys of the customersBarChart object
var keys = Object.getOwnPropertyNames(data);
// get the keys of the object in the first item in customersBarChart object
// and initialize an array
var attrs = Object.getOwnPropertyNames(data[keys[0]]).map(function(k) {
return {
key: k,
arr: []
};
});
// looping thru the attrs to collect the val for the array
attrs.forEach(function(attr) {
keys.forEach(function(k) {
attr.arr.push(data[k][attr.key]);
});
});
// drop the key property in attrs object
return attrs.map(function(attr) {
return attr.arr;
});
}
console.log(extractData(oData.customersBarChart));