Kyle
Kyle

Reputation: 1578

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

DISCLAIMER: I know how to do it when it's JSON, I need to know how to do it as being a STRING

I'm trying to get "ID":s and "children":, I kind of can get both but not in sequence. For now I can only get "ID":s or "children":s not both, how can I do it, any help is appreciated?

What I'm getting:

1,3,2

What I'd like to get

1,children,3,2

What I'm asking, basically, is to do these two in one (well, in a way that it will bring them in sequence).

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

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

My code is right below:

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

"Live long and prosper"

Thanks in advance.

Upvotes: 0

Views: 50

Answers (1)

rrk
rrk

Reputation: 15866

I am using jQuery. I presume you use it because of the tag you created.

DEMO

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>

Upvotes: 2

Related Questions