循环 JSON 并根据位置获取数组
Loop though a JSON and get arrays based on position
我有一个 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]
您可以使用 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())
这里是动态处理的方法。
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));
我有一个 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]
您可以使用 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())
这里是动态处理的方法。
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));