什么是从嵌套的javascript对象中删除属性的最佳方法?

什么是从嵌套的javascript对象中删除属性的最佳方法?

问题描述:

我有一个树对象如下,我试图删除items数组属性,如果它是空的。我不确定最好的方法吗?

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?

我正在考虑循环键,检查属性然后使用删除删除myJSONObject [prop] ...欢迎任何想法/想法?

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: []
                    }]
                }]
            }]
        }]
    }]
}]


这个sh应该做的工作( ES5 ):

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

相同的 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