js根据子节点获取树?

作者站长头像
站长
· 阅读数 14

已知树

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个回答
avatar
test
2024-07-18

这样?

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);
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容