Problem removing all attributes of an object that contains null values

1

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.

    
asked by anonymous 28.11.2018 / 23:26

1 answer

2

Is not just a if with its delete in the right place? In the case of if you have to check the number of keys that the object is after recursion, and if you have 0 remove the parent.

Example:

var objMapped = {
a: true,
b: false,
c: null,
d: undefined,
e: 10,
temFilhos: {
	nullAttr: null,
  nullAttr2: null,
  nullAttr3: null
}
};
console.log('antes', objMapped);

const removeEmptyAttrs = (objMapped) => {
  Object.keys(objMapped).forEach(key => {
    if (objMapped[key] && typeof objMapped[key] === 'object'){
      removeEmptyAttrs(objMapped[key]);
      if (Object.keys(objMapped[key]).length === 0){ //se pai ficou sem filhos
        delete objMapped[key]; //remove pai
      }
    }
    else if (objMapped[key] === null) delete objMapped[key];
  });
};
    
removeEmptyAttrs(objMapped);
console.log('depois', objMapped);
    
28.11.2018 / 23:57