gpt4 book ai didi

javascript - 如何显示结构化字符串的所有 `dad` 和 `son` ?

转载 作者:行者123 更新时间:2023-12-02 15:51:54 25 4
gpt4 key购买 nike

我完全自己编写了这段代码,因为我寻求帮助的每个人都会给出具有误导性且不适用于我的项目的答案,无论如何,我创建了一个代码来扫描字符串化的 JSON,简化它并提取它的 parent child ,问题是我的一个爸爸有一个 child 中的 child 。

我会尽力尽可能清楚地解释它:

我的树:

heyhey

生成并打印其结构:

[
{1[
{2}
{3[
{4}
]}
{5}
]}

{6[
{7}
]}
]

然后它的组织和打印如下:

爸爸:1 儿子:2

爸爸:3 岁,儿子​​:4

爸爸:6 岁,儿子​​:7 岁

但是,它缺少多个爸爸儿子,它应该是:

爸爸:1 儿子:2

爸爸:1 儿子:3

爸爸:1 儿子:5

爸爸:3 岁,儿子​​:4

爸爸:6 岁,儿子​​:7

我知道为什么它不起作用,但我还没有找到方法

感谢您迄今为止所做的一切,我们非常感谢您的帮助。

我的代码:

 var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child1","id":2},{"name":"child3","id":3,"is_open":true,"children":[{"name":"child2","id":4}]},{"name":"child2","id":5}]},{"name":"node2","id":6,"is_open":true,"children":[{"name":"child3","id":7}]}]';

var node;
var temp;

function dadSon(a) {
var each;
var numb;

a = '' + a;
for (var i = 0; i < a.length; i++) {
each = a.substring(i, i+1);
numb = isNaN(each);

if (each == '[') {temp += '['}
if (each == ']') {temp += ']'}
if (each == '{') {temp += '{'}
if (each == '}') {temp += '}'}

if (each == '"') {
if (a.substring(i, i + 5) === ('"id":')) {
temp += (a.substring(i + 5, i + 6));
}
}
}
temp = temp.replace('undefined','');
for (var h = 0; h < temp.length; h++){
each = temp.substring(h, h+1);
if(each == '{' && (temp.substring(h+2, h+3)) == '['){
node += '\nDad: '+temp.substring(h+1, h+2);
}
if((temp.substring(h-1, h)) == '[' && each == '{' && (temp.substring(h+2, h+3)) == '}'){
node += ' & Son: '+temp.substring(h+1, h+2);
}


}
node = node.replace('undefined','');
}

dadSon(data);
console.log(temp);
console.log(node);

更清晰地了解 JSON 对象:

[{
"name": "node1",
"id": 1,
"is_open": true,
"children": [{
"name": "child1",
"id": 2
}, {
"name": "child3",
"id": 3,
"is_open": true,
"children": [{
"name": "child2",
"id": 4
}]
}, {
"name": "child2",
"id": 5
}]
}, {
"name": "node2",
"id": 6,
"is_open": true,
"children": [{
"name": "child3",
"id": 7
}]
}]

最佳答案

您可以使用 JSON.parse 并使用递归函数迭代树:

(function printDadSon(data, parent) {
for(var i=0; i<data.length; ++i) {
if(parent) console.log('Dad: ' + parent + ' & Son: ' + data[i].id);
if(data[i].children) printDadSon(data[i].children, data[i].id);
}
})(JSON.parse(data));

关于javascript - 如何显示结构化字符串的所有 `dad` 和 `son` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31789788/

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