js根据子节点获取树?

已知树

const list = [
  {
    "id": "111",
    "text": "父节点1",
    "children": [
          {
            "id": "12",
            "text": "子节点1"
          },
          {
            "id": "14",
            "text": "子节点2"
          },
          {
            "id": "15",
            "text": "子节点3"
          }, 
    ]
  },
  {
    "id": "222",
    "text": "父节点2",
    "children": [
          {
            "id": "122",
            "text": "子节点11"
          },
          {
            "id": "144",
            "text": "子节点22"
          },
          {
            "id": "155",
            "text": "子节点33"
          }, 
    ]
  }
]

根据数组[12,14,122]如何渲染出来树形数据结构
想要的数据结构

const list = [
  {
    "id": "111",
    "text": "父节点1",
    "children": [
          {
            "id": "12",
            "text": "子节点1"
          },
          {
            "id": "14",
            "text": "子节点2"
          },
       
    ]
  },
  {
    "id": "222",
    "text": "父节点2",
    "children": [
          {
            "id": "122",
            "text": "子节点11"
          },
     
    ]
  }
]
阅读 1.4k
1 个回答

这样?

const filter = new Set(['12', '14', '122']);

list.map(({children: c, ...r}) => ({children: c.filter(i => filter.has(i.id)), ...r}))
    .filter(({children: c}) => c.length);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题