Created
May 20, 2016 12:59
-
-
Save marisusis/3ad2ab88e0309bc789c5f80c43730e01 to your computer and use it in GitHub Desktop.
Iterate over a JSON object and create a html list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var iter = function() { | |
var lev = 0; | |
var levels = [0,0,0,0]; | |
var uls = [$('<ul>')]; | |
return function(obj,level) { | |
for (var prop in obj) { | |
if (obj.hasOwnProperty(prop)) { | |
levels[lev]++; | |
if (typeof obj[prop] == 'object') { | |
uls[lev].append($('<li>').text(prop + ":")); | |
lev++; | |
uls[lev] = $('<ul>'); | |
iter(obj[prop]); | |
} else { | |
uls[lev].append($('<li>').text(prop + ":" + obj[prop])); | |
} | |
} | |
} | |
switch(lev) { | |
case 0: return $('<div>').append(uls[0]).html(); | |
break; | |
default: uls[lev-1].append(uls[lev]); | |
break; | |
} | |
lev--; | |
} | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment