js根据id数组匹配树形结构,查找所有的name?

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

树形结构如图js根据id数组匹配树形结构,查找所有的name?比如说有一个id数组arr=[2,7,8]根据这个数组获取所有id相同的name,返回一个name数组树形结构示例如下

tree = [
    {

        children: [
            { id: "1633361534304636930", name: "股份公司", parentId: "1633356939104866305", weight: 1 },
            {
                id: "1636300204602986497", name: "峰峰集团", parentId: "1633356939104866305", weight: 2, children: [
                    { id: "1636300266708045826", name: "邯郸洗选厂", parentId: "1636300204602986497", weight: 1, children: [] }
                ]
            }
        ],
        id: "1633356939104866305",
        name: "冀中能源",
        parentId: "0",
        weight: 1,
    },
    {

        children: [{ id: "7", name: "山东沙县", parentId: "2", weight: 7 }],
        id: "2",
        name: "沙县国际",
        parentId: "0",
        weight: 2
    },
    {

        children: [{ id: "1633372327221264385", name: "测试公司", parentId: "1631094382482067457", weight: 10 }],
        id: "1631094382482067457",
        name: "测试总部",
        parentId: "0",
        weight: 3
    },
    {

        children: [{ id: "3", name: "潍坊", parentId: "1", weight: 3 }],
        id: "1",
        name: "山东",
        parentId: "0",
        weight: 10
    }
]
回复
1个回答
avatar
test
2024-07-04

你可以用递归:

function findNamesByIds(tree, ids) {
  let result = [];

  function traverse(node) {
    if (ids.includes(node.id)) {
      result.push(node.name);
    }
    if (node.children) {
      for (const child of node.children) {
        traverse(child);
      }
    }
  }

  for (const node of tree) {
    traverse(node);
  }

  return result;
}

const tree = [
  // ...
];

const ids = [2, 7, 8];
const names = findNamesByIds(tree, ids);
console.log(names); // 输出: ["沙县国际", "山东沙县"]
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容