Skip to content

Instantly share code, notes, and snippets.

@westonplatter
Created December 23, 2013 02:16
Show Gist options
  • Select an option

  • Save westonplatter/8090935 to your computer and use it in GitHub Desktop.

Select an option

Save westonplatter/8090935 to your computer and use it in GitHub Desktop.
What's the fastest way to get all the ids into a single Javascript array?
{
"id": "0",
"item": [
{
"id": "1161736030",
"open": "1",
"text": "12\/14\/2013",
"item": [
{
"id": "1163797134",
"text": "CASE",
"item": [
{
"id": "1",
"text": "1214-1"
}
]
},
{
"id": "1163945744",
"text": "HAHA",
"item": [
{
"id": "2",
"text": "1214-2"
}
]
}
]
}
]
}
@westonplatter
Copy link
Author

not sure about performence, but this works,

// test.js

var jsonString = '{"id":"0", "item":[{ "id":"1161736030",  "open":"1",  "text":"12/14/2013", "item":[{ "id":"1163797134",  "text":"CASE", "item":[{ "id":"1",  "text":"1214-1"}]},{ "id":"1163945744",  "text":"HAHA", "item":[{ "id":"2",  "text":"1214-2"}]}]}]}';

var json = JSON.parse(jsonString);

var ids_array = [];

function get_ids(node, ids_array){
  ids_array.push(node.id);

  if(node.item != undefined){
    for (var i = node.item.length - 1; i >= 0; i--) {
      var child = node.item[i]
      get_ids(child, ids_array);
    };
  }
}

get_ids(json, ids_array);

console.log(ids_array);

terminal output

node test.js                                                         
[ '0', '1161736030', '1163945744', '2', '1163797134', '1' ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment