2
Context
I’m inside an application in Nodejs, where I have a very large object that has various attributes and also attributes objects that have children, and I have a situation where I can’t keep attributes that contain null values, so I made a function to remove attributes that contain null values, but it turned out that some objects had all null attributes, and so that generated another problem, because I can’t keep an object that has no child.
Goal
I need to remove attributes that are objects and no longer have children right after my scan that removes all attributes that contain null values.
Code
var objMapped = {
a: true,
b: false,
c: null,
d: undefined,
e: 10,
temFilhos: {
nullAttr: null,
nullAttr2: null,
nullAttr3: null
}
};
console.log('antes', objMapped);
//isso remove atributos de objeto que tem valores nulos, recursivamente percorrendo os objetos que tem filhos tambem
const removeEmptyAttrs = (objMapped) => {
Object.keys(objMapped).forEach(key => {
if (objMapped[key] && typeof objMapped[key] === 'object') removeEmptyAttrs(objMapped[key]);
else if (objMapped[key] === null) delete objMapped[key];
});
};
removeEmptyAttrs(objMapped);
console.log('depois', objMapped);
Note that in the code above I end up getting an object temFilhos
who actually no longer has a son, so it’s not right to keep him alive, I’d like my code to also remove the father if he doesn’t have any more children.
How come I didn’t think of it, bro? It was in my face kkkkkkkkkkkkkkkk.
– Paulo Roberto Rosa
@Pauloroberto We’re here to help :)
– Isac