How to remove an object (element) based on the property from nested obj. For example, I need to remove all objects with type: 'green' from obj tree if obj has children it will be also removed.
const obj = {
id: '01',
children: [
{
id: '02',
type: 'green',
children: [
{
id: '03',
type: 'black',
children: [],
},
{
id: '04',
type: 'green',
children: [
{
id: '05',
type: 'white',
children: [],
}
],
}
],
},
{
id: '06',
type: 'black',
children: [
{
id: '07',
type: 'green',
children: [],
},
{
id: '08',
type: 'white',
children: [
{
id: '09',
type: 'green',
children: [],
}
],
}
],
},
]
}
// expected result (if remove type: "green")
const expectedObj = {
id: '01',
type: 'orange',
children: [
{
id: '06',
type: 'black',
children: [
{
id: '08',
type: 'white',
children: [],
}
],
},
]
}
What I am trying to do
let match = false
const removeByType = (data, type) => {
match = data.some(d => d.type == type)
if (match) {
data = data.filter(d => d.type !== type)
} else {
data.forEach(d => {
d.children = removeByType(d.children, type)
})
}
return data
}
let data = obj.children
console.dir(removeByType(data, 'black'), { depth: null })
but { id: '03', type: 'black', children: [] } is still in the object tree
type: 'orange'forid '01'?