javascript找到深层嵌套的对象

ewo*_*ool 2 javascript lodash

我需要使用javascript在深层嵌套的对象数组中递归过滤对象,也许在lodash的帮助下.最干净的方法是什么,如果我不知道我的数组中有多少嵌套对象?

假设我有以下结构

[
  {
    label: "first",
    id: 1,
    children: []
  },
  {
    label: "second",
    id: 2,
    children: [
      {
        label: "third",
        id: 3,
        children: [
          {
            label: "fifth",
            id: 5,
            children: []
          },
          {
            label: "sixth",
            id: 6,
            children: [
              {
                label: "seventh",
                id: 7,
                children: []
              }
            ]
          }
        ]
      },
      {
        label: "fourth",
        id: 4,
        children: []
      }
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

我想找到一个id 6,如果它有子,则返回true,否则为false.

当然,如果我有一个类似的数据结构但具有不同数量的项目,它也应该工作.

Mar*_*yer 6

因为你只想要一个truefalse回答,您可以使用some()在递归,有效地做深度优先搜索,并使其相当简洁:

let arr = [{label: "first",id: 1,children: []},{label: "second",id: 2,children: [{label: "third",id: 3,children: [{label: "fifth",id: 5,children: []},{label: "sixth",id: 6,children: [{label: "seventh",id: 7,children: []}]}]},{label: "fourth",id: 4,children: []}]}];

function findNested(arr, id) {
    let found = arr.find(node => node.id === id)
    return found 
      ? found.children.length > 0 
      : arr.some((c) => findNested(c.children, id))

} 

console.log(findNested(arr, 6))  // True: found with children
console.log(findNested(arr, 7))  // False: found no children
console.log(findNested(arr, 97)) // False: not found
Run Code Online (Sandbox Code Playgroud)

  • @PatrickRoberts我认为他的意思是`found`存在但没有孩子.之后做DFS没有意义.话虽如此,很好的解决方案:) (2认同)