I stumbled upon the code snippet below online, which effectively and recursively eliminates properties from an object if their values are null, undefined, or 0
const removeEmpty = (obj) => {
Object.keys(obj).forEach(key =>
(obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
(obj[key] === undefined || obj[key] === null || obj[key] === 0) && delete obj[key]
);
return obj;
};
I am attempting to tweak it so that it also checks a property name for a value of "index". If it matches, do not delete the property even if its value is 0
For instance, if we process the following object
"page": {
"index": 0,
"title": "test",
"credits": undefined
}
the desired outcome would be
"page": {
"index": 0,
"title": "test"
}
while the current result looks like this
"page": {
"title": "test",
}