Q:

Best way to reorganize array of objects

I need reorganize and array of linked objects by id to only one tree object. The depth level is unknown, so that I think that it should be done recursively. What is the most efficient way?
I have the next array of objects:
const arrObj = [
  {
    "id": 1,
    "children": [
      {
        "id": 2
      },
      {
        "id": 3
      }
    ]
  },
  {
    "id": 2,
    "children": [
      {
        "id": 4
      },
      {
        "id": 5
      }
    ]
  },
  {
    "id": 3,
    "children": [
      {
        "id": 6
      }
    ]
  },
  {
    "id": 4
  }
]

I want restructure for have a only one object like a tree:
const treeObj = {
  "id": 1,
  "children": [
    {
      "id": 2,
      "children": [
        {
          "id": 4
        },
        {
          "id": 5
        }
      ]
    },
    {
      "id": 3,
      "children": [
        {
          "id": 6
        }
      ]
    }
  ]
}

Each object has other many properties.

A:

You can use a recursive mapping function over all the children.

const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 } ];
const res = arrObj[0];//assuming the first element is the root
res.children = res.children.map(function getChildren(obj){
  const child = arrObj.find(x => x.id === obj.id);
  if(child?.children) child.children = child.children.map(getChildren);
  return child || obj;
});
console.log(res);

