Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I am getting data back which includes nested json objects and would like to make a new array containing those json objects. 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"
    }
]
share|improve this question
    
and what have you tried? – Gary Aug 3 at 21:07
    
The new array is just data[0].products. Can the data be more complicated than this? – Barmar Aug 3 at 21:10
    
I have been doing data.products instead of data [0].products. thanks you so much! – tst22 Aug 3 at 21:39

3 Answers 3

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);
});
share|improve this answer

Use for loops to iterate over the data and place it in a new array.

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

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.