【问题标题】:Best way to reorganize array of objects重组对象数组的最佳方法
【发布时间】:2020-11-26 22:51:01
【问题描述】:

我需要通过 id 将链接对象的数组重新组织到只有一个树对象。深度级别是未知的,所以我认为应该递归地完成。什么是最有效的方法?

我有下一个对象数组:

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

我想要重组为只有一个对象,比如一棵树:

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

每个对象都有其他许多属性。

【问题讨论】:

    标签: javascript arrays json recursion


    【解决方案1】:

    您可以在所有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);

    【讨论】:

    • 是的,这是我的第一个解决方案,但我不确定它是否最有效
    • 与节点数量相比,此解决方案在线性时间内运行。实际上没有任何方法可以降低时间复杂度,因为总是需要遍历所有节点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2015-09-23
    • 2021-11-17
    • 2012-02-29
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多