[英]Loop through JSON nested array
使用此JSON对象:
{
"date_price": [
{
"date": "Jan 2000",
"price": 1394.46
},
{
"date": "Feb 2000",
"price": 1366.42
},
{
"date": "Mar 2000",
"price": 1498.58
},
{
"date": "Apr 2000",
"price": 1452.43
}
]
}
我该如何遍历它,并使用诸如此类的东西将每对日期价格保存在一个简单的数组中,例如:
var transformation = [];
transformation.push({date: i, price: d})
因为这里的问题是在控制台中,当我打印JSON对象时,它说它们是数组内的对象,所以我不能使用forEach()
循环
假设您已将JSON解析为对象...
var obj = JSON.parse(json);
... map
数据。
注意:根据您对我问题的回答,您需要嵌套数组结构,而不是对象数组(如您在问题中所要求的)。
ES5
var transformation = obj.date_price.map(function(el) {
return [ el.date, el.price ];
});
ES6
var transformation = obj.date_price.map(el => [ el.date, el.price ]);
输出值
[
["Jan 2000", 1394.46],
["Feb 2000", 1366.42],
["Mar 2000", 1498.58],
["Apr 2000", 1452.43]
]
编辑:由于您已经将JSON作为对象,因此您只需要从中获取date_price属性。 那正是您需要的对象类型的数组...所以...
var result = jsonObject.date_price; // THIS is your array here.
要么...
var result = jsonObject['date_price']; // THIS is your array here.
给出了先前的答案,其中假设一个JSON字符串...
简单地使用这个...
// This is just your JSON string above.
var text = '{ "date_price": [ { "date": "Jan 2000", "price": 1394.46 }, { "date": "Feb 2000", "price": 1366.42 }, { "date": "Mar 2000", "price": 1498.58 }, { "date": "Apr 2000", "price": 1452.43 } ] }';
// Parse it as an object.
var obj = JSON.parse(text);
// Get the date_price property, which is an array already.
var result = obj.date_price;
// Some output here, to illustrate...
console.log(result);
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
使用JSON.parse
和Array.map
函数的简单解决方案:
var jsonStr = '{"date_price": [{ "date": "Jan 2000", "price": 1394.46 },{"date": "Feb 2000", "price": 1366.42},{"date": "Mar 2000","price": 1498.58},{"date": "Apr 2000","price": 1452.43}]}', jsonObj = JSON.parse(jsonStr); //var transformation = jsonObj["date_price"]; // to get a nested array var transformation = jsonObj["date_price"].map(function(v){ return v; }); // to perform test artificial loop document.write("<pre>"+ JSON.stringify(transformation, 0, 4) + "</pre>");
您可以执行以下操作:
var abc = {
"date_price": [
{
"date": "Jan 2000",
"price": 1394.46
},
{
"date": "Feb 2000",
"price": 1366.42
},
{
"date": "Mar 2000",
"price": 1498.58
},
{
"date": "Apr 2000",
"price": 1452.43
}
]
}
var array = $.map(abc, function(value, index) {
return [value];
});
最简单的解决方案。 它已经是您需要的格式。 您只需要删除嵌套。
var obj = {
"date_price": [
{
"date": "Jan 2000",
"price": 1394.46
},
{
"date": "Feb 2000",
"price": 1366.42
},
{
"date": "Mar 2000",
"price": 1498.58
},
{
"date": "Apr 2000",
"price": 1452.43
}
]
};
var array = obj['date_price'];
就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.