'Indent object values in an array of nested objects in JavaScript

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: []
  }
]


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohìt Jíndal