Carlos Anez :
I need to filter an array with children
I'm using the .filter function and is not filtering the children the way I need
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"}]
}
Christian Fritz :
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);
})