我有一个看起来像这样的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 .. 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 }
说明文件: