I have an array of objects that have array within themselves. I want to loop through the object and delete any empty arrays that I have. The object is shown below:
let a=[{children:[{children:[1,2]},{children:[5,6]}]},
{children:[{children:[]},{children:[5,6]}]},
{children:[{children:[]},{children:[]}]},
{children:[]}]
I am trying to achieve the desired result by applying the code below but I am getting an error saying cannot read property 'children' of undefined.
function removeEmpty(array){
for(var i=array.length-1;i>=0;i--){
if(array[i].children){
if(array[i].children.length){
for(var j=array[i].children.length-1;j=>0;j--){
if(array[i].children[j].children){
removeEmpty(array[i].children[j])
}else{
array[i].splice[j,1]
}
}
if(!array[i].children.length){
array.splice(i,1)
}
}else{
array.splice(i,1)
}
}
}
}
removeEmpty(a)
Expected outcome:
expected outcome =[{children:[{children:[1,2]},{children:[5,6]}]},
{children:[{children:[5,6]}]}]
If there are adjustments I can make to the existing code or use a different approach please let me know. Thank you.