我有一个树对象,如下所示,我尝试删除 items 数组属性(如果它为空)。我不确定执行此操作的最佳方法是什么?
我正在考虑循环遍历密钥,检查属性,然后删除使用delete myJSONObject[prop]
...欢迎任何想法/想法吗?
[{
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: []
}]
}]
}]
}]
}]
}]
这应该可以完成工作(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 https://jsbin.com/huxeti/edit?html,js,console
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 https://jsbin.com/fesoko/edit?html,js,console
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)