简体   繁体   English

Javascript:从嵌套的json对象中制作新数组

[英]Javascript: Make new array out of nested json object

I am getting data back which includes nested json objects and would like to make a new array containing those json objects. 我正在获取包含嵌套json对象的数据,并想创建一个包含这些json对象的新数组。 So if I am getting 所以如果我得到

[
   {
        "number": 1,
        "products": [
            {
                "fruit": "apple",
                "meat": "chicken"
            },
            {
                "fruit": "orange",
                "meat": "pork"
            }
        ]
    }
]

I would like the new array to be 我希望新数组是

[
    {
        "fruit": "apple",
        "meat": "chicken"
    },
    {
        "fruit": "orange",
        "meat": "pork"
    }
]

 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); 

or test here 或在这里测试

Use for loops to iterate over the data and place it in a new array. 使用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 小提琴

This is assuming you want to flatten the products into a single array - I'm probably wrong about that... To test it, I moved a product into a separate parent in the data array. 这是假设您要将产品展平为一个数组-我对此可能是错的。为了进行测试,我将产品移到了数据数组中的单独父级中。

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM