here is simple data, i want to recursively remove the children attribute if the children attribute represents a empty array.
[{"name":"code","created":"2022-03-27T05:42:28.977Z","children":[],"path":"623ff9881a6e94547deaebed"}]
my code is as shown
function removeMeta(obj) {
let keys = Object.keys(obj);
for(let key in keys) {
console.log('.......',key,obj[key]);
if(typeof(obj[key]) == 'object'){
removeMeta(obj[key]);
}else if( key == 'children' && obj[key] ==[]){
delete obj[key];
}
}
}
but it doesn't seem to work, any idea
These are the issues:
The typeof the children property will be 'object', so your code will never perform the delete.
Remove the else from else if, so that that if is always executed.
obj[key] ==[] will always be false, as it compares with a newly created array -- by reference. Instead check the length:
obj[key].length == 0
The for loop should be a for..of loop, not a for..in loop
Corrected:
function removeMeta(obj) {
let keys = Object.keys(obj);
for(let key of keys) {
if(typeof(obj[key]) == 'object'){
removeMeta(obj[key]);
}
if( key == 'children' && obj[key].length == 0){
delete obj[key];
}
}
}
let arr = [{"name":"code","created":"2022-03-27T05:42:28.977Z","children":[],"path":"623ff9881a6e94547deaebed"}];
removeMeta(arr);
console.log(arr);