我有一个 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 }
文档:
https://stackoverflow.com/questions/15451290/
相关文章:
javascript - jQuery AJAX 调用带有 JSON 返回的 PHP 脚本
json - IE9 JSON 数据 "do you want to open or save th
xml - 为什么人们希望将 Json 和 XML 作为输出传递到他们的 REST 接口(inter
java - 将元数据添加到 RESTful JSON 响应的最佳实践是什么?
json - 是否为 null 有效 JSON(4 字节,仅此而已)
python - 在python中将SQL表作为JSON返回
wcf - DataContractJsonSerializer 和枚举
php - 如何在预先存在的 SQL 数据库之上使用 Elastic Search?