Home » Javascript » How to push data from a nested array, inside an array of objects, to a new array? while maintaining its nested structure

How to push data from a nested array, inside an array of objects, to a new array? while maintaining its nested structure

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have an array that contains multiple objects. These objects also contain arrays of objects like this:

const data =
    [
        {
            id: 1, name: "Jack", interests: 
            [
                {id: 9, name: "basketball"},
                {id: 8, name: "art"}
            ]
        },
        {
            id: 2, name: "Jenny", interests: 
            [
                {id: 7, name: "reading"},
                {id: 6, name: "running"}
            ]
        }
    ];

I would like to push both interests arrays into a new array like so:

newArray = 
    [
        [{id: 9, name: "basketball"}, {id: 8, name: "art"}],
        [{id: 7, name: "reading"},{id: 6, name: "running"}]
    ];

This pushes the data to the new array, but the data isn’t nested anymore this way:

data.map(v => { v.interests.map(x => { newArray.push({name: x.name, id:x.id}) }) })

How can I push the interests data to new array while keeping its nested structure?

Answers: