I have an array like this :
[
{
name: 'foo',
nestedArray: [
{
name: 'bar',
nestedArray: []
}
]
}
]
What's the best way to have a flatten array that looks like this?
[
{
name: 'foo',
nestedArray: [
{
name: 'bar',
nestedArray: []
}
]
},
{
name: ' bar',
nestedArray: []
}
]
You can try by iterating input array and moving out nested array objects into outer one. I hope this will work as per your expectation :
// Input array const inputArray = [ { name: 'foo', nestedArray: [ { name: 'bar', nestedArray: [] } ] } ]; // Result array const res = []; // Iterating input array and moving out nested array objects into outer one. inputArray.forEach((obj) => { res.push(obj); obj.nestedArray.forEach((nestedObj) => { res.push(nestedObj); }); }); // Assigning result console.log(res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.