简体   繁体   English

过滤数组对象子对象javascript

[英]Filter array object children javascript

I need to filter an array with children我需要过滤一个有孩子的数组

I'm using the .filter function and is not filtering the children the way I need我正在使用 .filter 函数并且没有按照我需要的方式过滤孩子

This is the object example这是对象示例

var arr =  {
       "items":[
          {
             "name":"Stackoverflow",
             "type":"development",
             "children":[
                {
                   "title":"web",
                   "titleName":"web site"
                },
                {
                   "title":"web",
                   "titleName":"site"
                }
             ]
          },
          {
             "name":"Jon Snow",
             "type":"actor",
             "children":[
                {
                   "title":"foo 2",
                   "titleName":"foo 3"
                },
                {
                   "title":"no foo",
                   "titleName":"bar 2"
                }
             ]
          }
       ]
    }

Code example:代码示例:

var searchWord = 'foo'

arr.items.filter(item => {
    return (item.children.some(c => c.titleName.indexOf(searchWord) > -1))
})

this will return the items that have the filter correctly but I need that filters the children in the return这将返回具有正确过滤器的项目,但我需要在返回中过滤子项

//The returned children
{ 
 "name":"Jon Snow",
 "type":"actor",
 "children":[{title: "foo 2", titleName: "foo 3"}, {title: "no foo", titleName: "bar 2"}]
}
//The expected should be 
{ 
 "name":"Jon Snow",
 "type":"actor",
 "children":[{title: "foo 2", titleName: "foo 3"}]
}

try this尝试这个

arr.items.filter(item => {
   if (item.children.some(c => c.titleName.indexOf(searchWord) > -1)){
        console.log(item);
      item.children=item.children.find(x=>x.titleName.indexOf(searchWord) > -1);
      return item
   }
})

https://jsfiddle.net/ahwctv8q/ https://jsfiddle.net/ahwctv8q/

You are not actually filtering the children, you are filtering only the top-level items.您实际上并未过滤子项,而是仅过滤顶级项目。

This should work correctly:这应该可以正常工作:

var searchWord = 'foo'
res = arr.items.filter(item => {
  item.children = item.children.filter(c => c.titleName.indexOf(searchWord) > -1);
  return (item.children.length > 0);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM