我怎么能从这个字符串和它的子字在一行中得到id

How can I get the IDs from this STRING and the word children in it in a row?

本文关键字:一行 id 怎么能 字符串      更新时间:2023-09-26

免责声明:我知道如何做到这一点,当它是JSON,我需要知道如何做到这一点作为一个STRING

我试着得到"ID": s和"children":,我可以同时得到,但不能按顺序得到。目前我只能得到"ID": s或"children": s,不能同时得到,我该怎么做,请帮助。

我得到的:

1, 3 2

我想要得到的

1,孩子3 2

基本上,我要求的是将这两者合二为一(以某种方式将它们按顺序排列)

var t1 = data.match(/"id":[0-9]+(,|})*/g);

var t2 = data.match(/"children":/g);

我的代码在下面:

var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays = [];
var t1 = data.match(/"id":[0-9]+(,|})*/g);
//arrays = t1;
for (var x = 0; x < t1.length; x++) {
  arrays.push(t1[x].match(/'d+/));
}
//var t2=data.match(/"children":/g);
alert(arrays /*+"'n'n'n'n'n"+t2*/ );

"万岁,兴旺发达"

我正在使用jQuery。我假定您使用它是因为您创建的标签。

var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays = [];
//convert you string to object
//or you can simply change your first row.
data = $.parseJSON(data);
//function to loop the array
function listNodes(inputVal){
    if(jQuery.isArray( inputVal )){
        $.each(inputVal, function(i,elem){
            arrays.push(elem.id);
            console.log(elem);
            if(jQuery.isArray( elem.children )){
                arrays.push('children');
                listNodes(elem.children);
            }
        })
    }
}
listNodes(data);
alert(arrays /*+"'n'n'n'n'n"+t2*/ );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>