gpt4 book ai didi

javascript - 使用javascript循环遍历具有多个子对象的JSON对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:28:15 26 4
gpt4 key购买 nike

我正在尝试遍历一个看起来像这样的 Json 对象

    [
{
"yang_type": "container",
"name": "c1",
"value": "",
"children": [
{
"yang_type": "",
"name": "type",
"value": "Uint32",
"children": []
},
{
"yang_type": "list",
"name": "DNS",
"value": "",
"children": [
{
"name": "type",
"value": "String",
"children": [],
"yang_type": ""
},
{
"yang_type": "leaf",
"name": "ip-address",
"value": "",
"children": [
{
"name": "type",
"value": "string",
"children": [],
"yang_type": ""
}
]
},
{
"yang_type": "leaf",
"name": "Domain",
"value": "",
"children": [
{
"name": "type",
"value": "string",
"children": [],
"yang_type": ""
}
]
}
]
}
]
}
]

我正在尝试这个逻辑,但它不会循环遍历第一个 child 的 child 。

while(m.children.length >= 1) {
if(m.yang_type!='' && m.name!=''){
{$log.error("parent:",m.yang_type,m.name);}
}
if(m.name!='' && m.value!=''){
{$log.error("child:",m.name,m.value);}
}
m = m.children[m.children.length - 1];
}

上面的代码并没有遍历所有的 child 。我做错了什么?

最佳答案

您尝试遍历数组。您的尝试不会以这种方式起作用。

您可以使用回调进行迭代,并将其用于子级的递归调用。

function loop(a) {
console.log(a.name); // process you data
Array.isArray(a.children) && a.children.forEach(loop); // check and iterate children
}

var data = [{ "yang_type": "container", "name": "c1", "value": "", "children": [{ "yang_type": "", "name": "type", "value": "Uint32", "children": [] }, { "yang_type": "list", "name": "DNS", "value": "", "children": [{ "name": "type", "value": "String", "children": [], "yang_type": "" }, { "yang_type": "leaf", "name": "ip-address", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }, { "yang_type": "leaf", "name": "Domain", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }] }] }];

data.forEach(loop);

使用缩进输出进行编辑。

function loop(level) {
return function (a) {
var i = level, s = '';
while (i--) {
s += ' ';
}
if (level) {
s += '*';
}
a.yang_type ?
console.log(s + a.yang_type + ' ' + a.name) :
console.log(s + a.name + ' ' + a.value);
Array.isArray(a.children) && a.children.forEach(loop(level + 1));
}
}

var data = [{ "yang_type": "container", "name": "c1", "value": "", "children": [{ "yang_type": "", "name": "type", "value": "Uint32", "children": [] }, { "yang_type": "list", "name": "DNS", "value": "", "children": [{ "name": "type", "value": "String", "children": [], "yang_type": "" }, { "yang_type": "leaf", "name": "ip-address", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }, { "yang_type": "leaf", "name": "Domain", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }] }] }];

data.forEach(loop(0));

关于javascript - 使用javascript循环遍历具有多个子对象的JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37763663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com