Javascript 循环通过JSON并根据位置获取数组
我有一个json对象和一个伪json响应。 我需要遍历它,得到每个坐标的新数组,每个循环一个 示例JSON:Javascript 循环通过JSON并根据位置获取数组,javascript,ecmascript-5,Javascript,Ecmascript 5,我有一个json对象和一个伪json响应。 我需要遍历它,得到每个坐标的新数组,每个循环一个 示例JSON: customersBarChart: { "2014": { "x": 1, "y": 5, "z":10 }, "2015": { "x": 8, "y": 2, "z"
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(让o在obj中)
在对象上循环,并从中获取值。现在,通过将obj[o]
中的数据推送到指定数组的末尾,可以创建3个单独的数组
让obj={
"2014": {
“x”:1,
“y”:5,
“z”:10
},
"2015": {
“x”:8,
“y”:2,
“z”:5
},
}
设arr1=[]
设arr2=[]
设arr3=[]
for(让o在obj中){
arr1.push(对象[o].x)
arr2.push(对象[o].y)
arr3.push(对象[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));
你自己有没有尝试过?可能是重复的当然我尝试了很多,但我无法得到我需要的!所以我请求你的帮助,你应该分享其中的一个尝试,最好的一个。你会得到更多的帮助,并期待有人写下整件事。格式化的JSPN,更正的英语。谢谢你尝试帮助,但我需要它更动态的i[x,y,x]是虚拟数据