0

I have an array of object like this:

 example = [
  {
    id: 1,
    child: [
      {
        id: 1,
        name: "child 1",
      },
    ],
  },
  {
    id: 2,
    child: [
      {
        id: 2,
        name: "child 2",
      },
      {
        id: 3,
        name: "child 3",
      },
    ],
  },
];

and I want to get an array of child objects like this:

[{...},{...},{...}]

I tired to loop through with map but I'm getting an array of two object.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Its not clear what you need . Do you need an array of objects with your `child` values ? – Shyam May 24 '21 at 08:05

1 Answers1

0

You can map the child arrays to a new array and flatten them.

Array.prototype.flatMap

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

example = [
  {
    id: 1,
    child: [
      {
        id: 1,
        name: "child 1",
      },
    ],
  },
  {
    id: 2,
    child: [
      {
        id: 2,
        name: "child 2",
      },
      {
        id: 3,
        name: "child 3",
      },
    ],
  },
];

const newArray = example.flatMap(({ child }) => child);

console.log(newArray);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181