从JSON对象中删除元素

时间:2013-03-16 15:55:05

标签: javascript jquery json

我有一个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": ""
            }
        }
    }]
}

我希望有一个函数可以删除“children”为空的元素。我该怎么做?我不是要求答案,只是建议

2 个答案:

答案 0 :(得分:55)

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

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

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

使用delete关键字

可以删除对象的属性
var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

文档:

答案 1 :(得分:2)

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])
}