I have nested tree object I would like filter through without losing structure
var items = [
{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}]
}]
}
];
so for example if id == 2 remove object with id 2 and his children
if id == 3 only remove object with id 3
this's just apiece of object to make question clean but the object it self contains more and more :)
using vanilla javascript, _lodash or Angular2 it's okay
thank you
Use recursive function:
If it's ok for your case to use Lodash+Deepdash, then:
Here is a demo Codepen
You can create recursive function using
filter()
and also continue filtering children if value is Array.Update: As Nina said if you know that children is property with array you don't need to loop keys you can directly target
children
property.You could use an iterative approach with
Array#some
and call the callbackiter
recursive for the children. I found, splice.