javascript - 从 JSON 对象中删除元素

标签 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": ""
            }
        }
    }]
}

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

最佳答案

要遍历对象的键,请使用 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 }

文档:

关于javascript - 从 JSON 对象中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15451290/

相关文章:

javascript - 如何识别正在改变样式的内容

jquery - 如何删除特定父div的所有内部div?

Java Jackson Custom Polymorphc Deserializer 用于加密/解密字段

java - Jackson:简单的映射

C# .WithJson 无效 JSON 错误

javascript - 如何在 Javascript c3 图表中添加带间距的标签?

javascript - 使用js cloneNode复制<div>模板并修改children

javascript - 在 ng-repeat View 和 json 对象中添加元素

javascript - 关注前面的输入时显示下一个 div,然后再次隐藏它(CSS3、JavaScript、Jquery)

javascript - 使用 .find() 定位多个类以将当前类存储为变量