我正在获取包含嵌套json对象的数据,并希望创建一个包含这些json对象的新数组。所以,如果我得到了
[
{
"number": 1,
"products": [
{
"fruit": "apple",
"meat": "chicken"
},
{
"fruit": "orange",
"meat": "pork"
}
]
}
]
我希望新数组
[
{
"fruit": "apple",
"meat": "chicken"
},
{
"fruit": "orange",
"meat": "pork"
}
]
答案 0 :(得分:0)
var A = [ { "number": 1, "products": [ { "fruit": "apple", "meat": "chicken" }, { "fruit": "orange", "meat": "pork" } ] } ];
var B = [];
A.forEach(function(number) {
B = B.concat(number.products);
});
console.log(B);
答案 1 :(得分:0)
使用for循环迭代数据并将其放入新数组中。
var data = [{
"number": 1,
"products": [{
"fruit": "apple",
"meat": "chicken"
}, {
"fruit": "orange",
"meat": "pork"
}]
}],
allProducts = [];
for(var i=0;i< data.length; i++) {
var products = data[0].products;
for(var j=0;j< products.length; j++) {
allProducts.push(products[j]);
}
}
console.log(allProducts);
<强> Fiddle 强>
答案 2 :(得分:0)
这假设您想要将产品展平为单个数组 - 我可能错了...为了测试它,我将产品移动到数据数组中的单独父级。
var data = [
{
"number": 1,
"products": [
{
"fruit": "apple",
"meat": "chicken"
}
]
},
{
"number": 2,
"products": [
{
"fruit": "orange",
"meat": "pork"
}
]
}
];
var products = data.reduce(function(x, y) {
return x.products.concat(y.products);
});