Concatenating child array to parent

Tags: , ,



Right now I have an array of object with children that also have an array of objects.

 [
  {
    "code": "mock-code",
    "name": "mock-name",
    "children": [
      {
        "code": "mock-child-code",
        "name": "mock-child-name",
      },
      {
        "code": "mock-child-code",
        "name": "mock-child-name",
      },
    ],
  },
 {
    "code": "mock-code",
    "name": "mock-name",
    "children": [],
  },
 {
    "code": "mock-code",
    "name": "mock-name",
    "children": [
      {
       "code": "mock-code",
       "name": "mock-name",
      }
    ],
  }
]

I want to extract the children array and concat them to the parent array like below.

 [
  {
    "code": "m1",
    "name": "mock-name",
    "children": [
      {
        "code": "mc-1",
        "name": "mn-1",
      },
      {
        "code": "mc-2",
        "name": "mn-2",
      },
    ],
  },
 {
    "code": "m2",
    "name": "mock-name",
    "children": [],
  },
 {
    "code": "mm3",
    "name": "mock-name",
    "children": [
      {
       "code": "mc-3",
       "name": "mn-3",
      }
    ],
  }
  {
    "code": "mc-1",
    "name": "mn-1",
  },
  {
    "code": "mc-2",
    "name": "mn-2",
  },
   {
    "code": "mc-3",
    "name": "mn-3",
  }
] 

What are someways to do this. I’m currently looping though the child array creating a new array checking if it’s not empty. It all seems a bit messy. Is there a clean way to do this?

   let fullList = New Array()
   parentData.forEach(element => {
      if (!!element.children.length) {
       fullList.push(element.children);
      }
    });

   return parentData.concat(fullList);

This isn’t giving me the desired results since it’s adding another array to the parent object but this is where I am at.

Answer

const newArray = originalArray.flatMap(element => [element, ...element.children])

This should do it, and as a bonus will preserve the order (parent1, parent1’s children, parent2, parent2’s children etc.)

Of course, this works if you have only one level of nesting. If you have greater depth level, that would be a bit more complex, probably using Array.prototype.reduce().



Source: stackoverflow