Whats the best way to remove a property from nested javascript Object?

女生的网名这么多〃 提交于 2019-12-07 03:46:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!