从JSON对象中删除元素 [英] Remove element from JSON Object
本文介绍了从JSON对象中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json数组看起来像这样:
I have a json array which looks something like this:
{
"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": ""
}
}
}]
}
我希望有一个函数可以删除具有孩子们空虚。我该怎么做?我不是要求答案,只是建议
I would like to have a function which removes the elements which has the "children" empty. How can I do it? I am not asking for the answer, only suggestions
推荐答案
要迭代对象的键,请使用 for .. in
loop:
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
要测试空子项的所有元素,可以使用递归方法:遍历所有元素并递归测试它们的子项。
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
可以使用 delete
关键字来删除对象的属性:
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
文档:
- https:// developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
- https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete
- https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete
这篇关于从JSON对象中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文