Javascript 做一个树形图[{quot;id";1},{quot;id";2,'children";:[{{quot;id";3},{quot;id";4},{quot;id";5,'children";:[{quot;id";6}]

Javascript 做一个树形图[{quot;id";1},{quot;id";2,'children";:[{{quot;id";3},{quot;id";4},{quot;id";5,'children";:[{quot;id";6}],javascript,Javascript,我在javascript中有一个字符串变量,如下所示: var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children"[{"id":6}]}]'; now i want to create a tree from this in which # 1 and 2 will at same level # 3 ,4 ,5 will be the sub nodes of 2. # 6 will be the s

我在javascript中有一个字符串变量,如下所示:

var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children"[{"id":6}]}]';
now i want to create a tree from this in which
# 1 and 2 will at same level
# 3 ,4 ,5 will be the sub nodes of 2.
# 6 will be the sub node of 5.
请通过javascript或jquery帮助创建一个树,形成这个树变量。
变量。

在我看来,没有太多。我发现了一些拼写错误,但除此之外,它是一个JSON结构。在第二个“children”之后缺少冒号,也缺少一些右括号。我删除了引号

var tree = [{
      "id" : 1
    }, {
      "id" : 2,
      "children" : [{
          "id" : 3
        }, {
          "id" : 4
        }, {
          "id" : 5,
          "children" : [{ //missing colon
              "id" : 6
            } //missing bracket
          ] //missing bracket
        }
      ]
    }
  ];
  console.log(JSON.stringify(tree[0]));
  console.log(JSON.stringify(tree[1]));
  console.log(JSON.stringify(tree[1].children));

只是提醒一下,你有几个拼写错误-要找到它们,把你的字符串放到解析器中,在那里有一些拼写错误,请参见注释。 无论如何,您只需使用
JSON.parse进行转换

var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6}]}]}]'; 
//Missing ':' near 'children' and '}]' at the end

var array = JSON.parse(tree);

你能说得更具体些吗?
是一种
数据结构
-。你到底需要什么?你想从树上生成树吗!
var tree='[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6}]}]}]'; 
//Missing ':' near 'children' and '}]' at the end

var array = JSON.parse(tree);