javascript - 在对象数组中查找包含对象数组中的子对象的值

标签 javascript arrays ecmascript-6

我有一个对象数组,其中包含对象数组中的子项,我需要在父数组中查找值或在该数组的子项中查找值等。可能是递归的。我试过这样:

var array = [
  {
    id: 1,
    value: 'value',
    children: null
  },
  {
    id: 2,
    value: 'my value',
    children: [
      {
        id: 'child1',
        value: 'my value',
        children: null
      },
      {
        id: 'child2',
        value: 'value',
        children: null
      },
      {
        id: 'child3',
        value: 'value,
        children: [
          {
            id: 'childchild1',
            value: 'my value',
            children: null
          }
        ]
      }
    ]
  },
  {
    id: 3,
    value: 'value',
    children: null
  },
  {
    id: 4,
    value: 'my value',
    children: null
  }
]


function find(searchData, target){
  return target.filter((f)=>{
    if(f.value.includes(searchData)){
      return true
    }
    if(f.children){
      return find(searchData, f.children)
    }
  })
}

find('my', array)

它返回源数组,但我需要包含文本“我的”的数组

最佳答案

因为你有一个嵌套结构,你不能使用 .filter 来获取所有嵌套对象 - .filter 只会返回给你最顶层的匹配对象等级。相反,在初始调用时定义一个空数组,然后在项目通过测试时 push 到该数组,并将该数组传递给每个递归调用。最后,返回该数组:

var array=[{id:1,value:'value',children:null},{id:2,value:'my value',children:[{id:'child1',value:'my value',children:null},{id:'child2',value:'value',children:null},{id:'child3',value:'value',children:[{id:'childchild1',value:'my value',children:null}]}]},{id:3,value:'value',children:null},{id:4,value:'my value'}];

function find(searchData, target, accum=[]){
  target.forEach((f)=>{
    if(f.children){
      find(searchData, f.children, accum)
    }
    if(f.value.includes(searchData)){
      accum.push(f);
    }
  });
  return accum;
}

console.log(find('my', array));

(通过浏览器控制台可能比通过堆栈代码段控制台更容易看到结果)

关于javascript - 在对象数组中查找包含对象数组中的子对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865538/

相关文章:

javascript - jQuery 显示和隐藏下一个 <tr> 中的下一个 div

javascript - React.js 使用 map 遍历对象键和值

c# - 与索引比较查找数组中的值

Javascript 按整数字段对对象进行排序

javascript - Webpack 无法加载json 文件,如何定位本地json 文件并使用http.get 和AngularJS 加载该文件

javascript - 调试位于局部 View 中的脚本

javascript - 停止 onmouseenter 在 Chrome 和 Firefox 中重复触发

arrays - Mongo 过滤/查找嵌入数组中匹配条件的所有元素并返回周围文档?

javascript - react js将对象添加到状态数组

javascript - 在 Javascript 中正确处理多个调用