Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Created July 9, 2015 16:42
Show Gist options
  • Save simplelife7/92d5b3e6307879292e96 to your computer and use it in GitHub Desktop.
Save simplelife7/92d5b3e6307879292e96 to your computer and use it in GitHub Desktop.
【JS】遍历JSON所有节点
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
//called with every property and it's value
function process(key,value) {
log(key + " : "+value);
}
function traverse(o,func) {
for (i in o) {
func.apply(this,[i,o[i]]);
if (typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i],func);
}
}
//that's all... no magic, no bloated framework
traverse(o,process);
function traverse(jsonObj) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
// k is either an array index or object key
traverse(v);
}
}
else {
// jsonOb is a number or string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment