Problem when removing all attributes of an object containing null values

Asked

Viewed 383 times

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.

1 answer

2


Not enough a if with its delete in the right place ? In case the if you need to check the amount of keys that the object is left to after recursion, and if you get 0 removes the father.

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);

  • How come I didn’t think of it, bro? It was in my face kkkkkkkkkkkkkkkk.

  • @Pauloroberto We’re here to help :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.