什么是从嵌套的javascript对象中删除属性的最佳方法? [英] Whats the best way to remove a property from nested javascript Object?

查看:72
本文介绍了什么是从嵌套的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

这篇关于什么是从嵌套的javascript对象中删除属性的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆