繁体   English   中英

从JSON对象中删除元素

[英]Remove element from JSON Object

我有一个json数组,看起来像这样:

  {
    "id": 1,
    "children": [
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    },
    {
        "id": 2,
        "children": {
            "id": 3,
            "children": {
                "id": 4,
                "children": ""
            }
        }
    }]
}

我想有一个函数删除“子”空的元素。 我该怎么做? 我不是要求答案,只是建议

要遍历对象的键,请使用for .. in循环:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

要测试空子项的所有元素,可以使用递归方法:遍历所有元素并递归测试它们的子项。

可以使用delete关键字delete对象的属性:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

文档:

的jsfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM