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