Skip to content

Instantly share code, notes, and snippets.

@subtubes-io
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save subtubes-io/11270340 to your computer and use it in GitHub Desktop.

Select an option

Save subtubes-io/11270340 to your computer and use it in GitHub Desktop.
JavaScript Recursion Example
(function () {
"use strict";
var list = [
{ name: "level 1", obs: [
{name: "level 2", obs: [
{name: "level 3 a"},
{name: "level 3 b"}
]}
]},
{name: "section 2"}
];
function recurse(arr,prop, spacer) {
var len = arr.length,
i = 0,
str = "",
curr;
spacer = spacer || "";
for (i; i < len; i++) {
str += spacer + arr[i].name + "\n";
curr = arr[i];
if (curr[prop] && curr[prop].length) {
str += recurse(curr[prop], prop, spacer + "\t");
}
}
return str;
}
console.log(recurse(list, 'obs'));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment