I am trying to filter a nested array based on the value of an element field. The array that needs to be filtered is shown below. I want to filter by the checked value of each element. If the value is true, I want to keep the element; if false, discard it.
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: []
}
]
This is the desired result: (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: []
}
]
}
]
Below is my attempted solution (which does not 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)
})
The node.children.filter
never executes if the first level data has checked
equal to true.
What should I do to ensure that the children
recursion continues regardless of the parent
's checked status?
Thank you!