Context
I'm inside an application in NodeJS, where I have a fairly large object that has several attributes and also attributes objects that have children, and I have a situation where I can not keep the attributes containing null values, so I did a function to remove the attributes that contain null values, but it turned out that some objects had all the null attributes, and then that caused another problem because I can not keep an object that has no child.
Objective
I need to remove attributes that are objects and have no more 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 above code I eventually get a temFilhos
object that actually no longer has any children, so it is not correct to keep it alive, I would like my code to also remove the parent if it does not more children.