jQuery 从 JSON 对象中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15451290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove element from JSON Object
提问by Stack Overfolow
I have a json array which looks something like this:
我有一个 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": ""
}
}
}]
}
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
我想要一个函数来删除“孩子”为空的元素。我该怎么做?我不求答案,只求建议
回答by Lekensteyn
To iterate through the keys of an object, use a for .. in
loop:
要遍历对象的键,请使用for .. in
循环:
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.
要测试所有元素的空子元素,您可以使用递归方法:遍历所有元素并递归测试它们的子元素。
Removing a property of an object can be done by using the delete
keyword:
可以使用delete
关键字删除对象的属性:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
文档: