问题
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: []
}]
}]
}]
}]
}]
}]
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/14344356/whats-the-best-way-to-remove-a-property-from-nested-javascript-object