JS 合并树状结构 保留树状结构 属性不丢失

树状结构1

const tree1 = [
  {
    id: 1,
    title: "title0039405",
    value: "csjd2c6s2",
    children: [
      {
        id:11,
        title: "title535655",
        title: 11,
        children:[]
      },
      {
        id:12,
        children:[
          {
            id: 121,
            children: []
          }
        ]
      }
    ]
  }
]

树状结构2

const tree2 = [
  {
    id: 1,
    title: "title0039405",
    children: [
      {
        id: 12,
        children: [
          {
            id: 121,
            children: [
              {
                id: 1211,
                children: []
              }
            ]
          },
          {
            id: 122,
            children:[]
          },
          {
            id: 123,
            children:[]
          }
        ]
      },
      {
        id: 13,
        children: []
      }
    ]
  }
]

期望:

const newTree = [
  {
    id: 1,
    title: "title0039405",
    value: "csjd2c6s2",
    children: [
      {
        id:11,
        title: "title535655",
        children:[]
      },
      {
        id:12,
        children:[
          {
            id: 121,
            children: [
              {
                id: 1211,
                children: []
              }
            ]
          },
          {
            id: 122,
            children:[]
          },
          {
            id: 123,
            children:[]
          }
        ]
      },
      {
        id: 13,
        children: []
      }
    ]
  }
]

备注:
两颗树的属性有些许不同,需要一起合并,当均存在时,树2覆盖树1。

阅读 2.3k
1 个回答

function mergeTree(target, source) {
    if (!target?.length || !source?.length) {
        return;
    }

    const more = [];
    source.forEach(sNode => {
        const tNode = target.find(tn => tn.id === sNode.id);
        if (!tNode) {
            more.push(sNode);
            return;
        }

        const { children: sChildren, ...props } = sNode;
        Object.assign(tNode, props);
        mergeTree(tNode.children, sChildren);
    });
    target.push(...more);

    return target;
}

mergeTree(tree1, tree2);

其实就是一个递归,对每一层对应的 Node 的 children 都当作子树来进行递归调用,递归前先把节点的非 children 属性合并起来。

关于树,可以参考阅读:

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题