Can someone help here:
- Working good with objects
- But code is breaking in empty Arrays
const removeEmptyProperties = (obj) => {
obj = Array.isArray(obj) ? obj.filter(val => val !== 'null' || val !== 'undefined') : obj;
Object.keys(obj).forEach((key) => {
//recursive for nested objects
if (obj[key] && typeof obj[key] === 'object')
removeEmptyProperties(obj[key]);
//remove empty properties
else if (
typeof obj[key] !== 'boolean' &&
(obj[key] == null || obj[key] == '')
)
delete obj[key];
//remove empty objects
if (
typeof obj[key] !== 'boolean' &&
typeof obj[key] === 'object' &&
Object.keys(obj[key]).length == 0
)
delete obj[key];
});
};
let data = {
questionDetails: [
{
trees: 123,
template: {
id : null
}
},
{
trees: 123,
},
],
};
delete data.questionDetails[1];
removeEmptyProperties(data);
console.log(data); => { questionDetails: [ { trees: 123 }, <1 empty item> ] }
But expected result should be { questionDetails: [ { trees: 123 } ] }, My code is breaking in empty array
deletedeletes properties of an object. It is not meant to be used to "delete" entries in an array..