Using the following sample data, I am attempting remove object entries where the array children
is empty.
So based on allData
below, the following would be removed alone:
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
Since "children": []
is empty.
I have tried the following below but unsure how to achieve my expected result and target the specific object entry.
Based on comments below, a recursive solution is required but I am not sure how to do this.
let allData = {
"name": "Max",
"info": "Max info",
"section_id": 1,
"children": [
{
"childName": "Sam",
"childAge": 5
},
{
"name": "Helen",
"info": "Helen info",
"section_id": 2,
"children": [
{
"childName": "Sarah",
"childAge": 11
},
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
]
}
]
}
let children = allData.children
const myData = children.filter(v => !v.children || v.children.length > 0)
myData.forEach((element, index) => {
if (element) {
console.log(element)
}
});
The following console log is produced:
{
"childName": 'Sam',
"childAge": 5
}
{
"name": "Helen",
"info": "Helen info",
"section_id": 2,
"children": [
{
"childName": "Sarah",
"childAge": 11
},
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
]
}
I was looking at using the index
to splice the array in order to remove:
{
"name": "Tom",
"info": "Tom info",
"section_id": 3,
"children": []
}
Any help would be great.