I have a tree object as below, I am trying to remove the items array property if it's empty. I am not sure on the best approach to do this?
I am thinking of looping through the key, check the property and then remove using delete myJSONObject[prop]
... Any thoughts / ideas are welcome?
[{
text: "TreeRoot",
items: [{
text: "Subgroup1",
items: []
}, {
text: "Subgroup2",
items: []
}, {
text: "Subgroup3",
items: [],
items: [{
text: "subgroup5",
items: [{
text: "subgroup6",
items: [{
text: "subgroup7",
items: [{
text: "subgroup8",
items: []
}]
}]
}]
}]
}]
}]
Remove Property from an Object The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.
The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned. However, it is important to consider the following scenarios: If the property which you are trying to delete does not exist, delete will not have any effect and will return true .
To remove a property from all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.
This should do the job (ES5):
function removeEmpty(obj) {
Object.keys(obj).forEach(function(key) {
(key === 'items' && obj[key].length === 0) && delete obj[key] ||
(obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key])
});
return obj;
};
JSBIN
Same in ES6:
const removeEmpty = (obj) => {
Object.keys(obj).forEach(key =>
(key === 'items' && obj[key].length === 0) && delete obj[key] ||
(obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key])
);
return obj;
};
JSBIN
You can have recursive algorithm that at each step either removes items
array and returns, or recursively processes each individual object of the array.
I would also try to do this on the server-side. It will save a lot of complexity, memory, and processing time. There are usually ways of "excluding" empty arrays from the JSON encoded string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With