简体   繁体   English

重组对象数组的最佳方法

[英]Best way to reorganize array of objects

I need reorganize and array of linked objects by id to only one tree object.我需要通过 id 将链接对象的数组重组为只有一棵树 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:我想重组为只有一个 object 像一棵树:

const treeObj = {
  "id": 1,
  "children": [
    {
      "id": 2,
      "children": [
        {
          "id": 4
        },
        {
          "id": 5
        }
      ]
    },
    {
      "id": 3,
      "children": [
        {
          "id": 6
        }
      ]
    }
  ]
}

Each object has other many properties.每个 object 都有其他许多属性。

You can use a recursive mapping function over all the children .您可以对所有children使用递归映射 function 。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM