从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": ""

}

}

}]

}

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

回答:

要遍历对象的键,请使用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://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Working_with_Objects
  • https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Statements/for...in
  • https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Operators/delete

以上是 从JSON对象中删除元素 的全部内容, 来源链接: utcz.com/qa/417694.html

回到顶部