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

时间:2015-08-03 14:22:23

标签: javascript

我完全由我自己制作了这段代码,因为我请求帮助的每个人都会给出误导并且不适用于我的项目的答案,无论如何,我创建了一个代码来扫描字符串化的JSON,简化它并提取它{{ 1}}和parents,问题是我的children之一在孩子中有一个孩子。

我会尽我所能来解释它

我的树:

heyhey

生成并打印其结构:

dad

然后按照以下方式组织和打印:

爸爸:1&儿子:2

爸爸:3&儿子:4

爸爸:6&儿子:7

但是,它缺少多个[ {1[ {2} {3[ {4} ]} {5} ]} {6[ {7} ]} ] dad,它应该是:

爸爸:1&儿子:2

爸爸:1&儿子:3

爸爸:1&儿子:5

爸爸:3&儿子:4

爸爸:6&儿子:7

我知道为什么它不能正常工作,但我还没有办法做到这一点

感谢您的到目前为止,感谢任何帮助。

我的代码:



son




更清晰的JSON对象视图:

 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);

1 个答案:

答案 0 :(得分:2)

您可以使用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));