I am facing a challenge with the array structure below:
const obj = [
{
"description": "PCS ",
"children": [
null,
{
"name": "Son",
"children": [
{
"name": "Son2",
"children": [],
},
{
"name": "Son3",
"children": [],
}
],
},
{
"name": "Son4",
"children": [
{
"name": "Son4",
"children": [],
},
{
"name": "Son4",
"children": [],
}
],
},
{
"name": "Son",
"children": [
{
"name": "Son2",
"children": [
{
"name": "More"
"children": [
null,
{
...other objects
}
],
}
],
},
],
},
],
},
{
"name": "awesome",
"children": [
{
"children": [],
"active": true
}
],
},
{
"name": "children",
"children": []
},
]
My aim is to eliminate all occurrences of null
within the children's arrays. The issue lies in the nested nature of the arrays, as there could be multiple levels of nesting containing null elements.
I attempted using a recursive function which wasn't successful:
function deactiveRecursive(obj) {
if (!obj) return;
return {
...obj,
children: obj.children.filter(child => child !== null)
};
}
function removeRecursive() {
return obj.filter((item) => {
return {
...item,
children: item["children"].filter((c) => deactiveRecursive(c))
}
})
}
I have previously applied a similar approach to remove an item based on a specific id (it worked, but I wanted to completely remove the objects instead of returning null or undefined). However, due to the necessity of having a return value, I couldn't simply erase it. This logic resulted in the objects being replaced with null.
const deact = JSON.stringify(
this.array,
(_, nestedValue) => {
if (nestedValue && nestedValue['_id'] === MyWanteIdToRemove._id) {
return null
}
return nestedValue
}
)