How do you loop through a complex JSON tree of objects and arrays in JavaScript?

This is an example of depth-first traversal

Answer by Steve Schafer:

What you want is a tree traversal routine. Because of the quirks of JavaScript, you have to treat the three main kinds of JavaScript "things" (objects, arrays, primitive values) differently. Here's a simple traversal function that accepts any JavaScript object tree and traverses it, printing out an indented view of the tree:

function traverse(x, level) {
  if (isArray(x)) {
    traverseArray(x, level);
  } else if ((typeof x === 'object') && (x !== null)) {
    traverseObject(x, level);
  } else {
    console.log(level + x);
  }
}

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]';
}

function traverseArray(arr, level) {
  console.log(level + "<array>");
  arr.forEach(function(x) {
    traverse(x, level + "  ");
  });
}

function traverseObject(obj, level) {
  console.log(level + "<object>");
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      console.log(level + "  " + key + ":");
      traverse(obj[key], level + "    ");
    }
  }
}

This is an example of depth-first traversal (there are other kinds). To use, just replace the

console.log()

calls with "real" code.

How do you loop through a complex JSON tree of objects and arrays in JavaScript?

Advertisements

Leave a comment

Filed under Life

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s