I want to filter a nested array by element field value. Here is the array need to filter. I want to filter by element checked value, If value equal true, return, false, discard the element.
let rawData =[
{
name: 'red',
checked: true,
children: [
{
name: 'red1',
checked: false,
children: [
{
name: 'red11',
checked: true,
children: [
{
name: 'red111',
checked: false,
children: [
{
name: 'red1111',
checked: true,
children: []
}
]
}
]
}
]
}
]
},
{
name: 'blue',
checked: false,
children: [
{
name: 'blue1',
checked: true,
children: [
{
name: 'blue11',
checked: true,
children: []
},
{
name: 'blue12',
checked: false,
children: []
},
]
}
]
},
{
name: 'yellow',
checked: false,
children: []
}
]
Here is the result i want. (Filter every element and return it with checked equal true. If not equal true, just discard.
let result =[
{
name: 'red',
checked: true,
children: [
{
name: 'red11',
checked: true,
children: [
{
name: 'red1111',
checked: true,
children: []
}
]
}
]
},
{
name: 'blue1',
checked: true,
children: [
{
name: 'blue11',
checked: true,
children: []
}
]
}
]
Here is my solution. (won't work)
let result = rawData.filter(node => {
function getCheckedData (node) {
if (node.checked === true) {
return node
}
if (node.children.length) {
node.children.filter(c => {
getCheckedData(c)
})
}
return getCheckedData(node)
})
node.children.filter never execute if first level data checked equal true.
What should i do to make make children recursive go on no matter parent checked status.
Thanks~~
"false"? What do you expect that to equate to? True? False?red1111is a grandchild ofred11. But in the output it's a child. Are you sure you don't want a flat list for the output?