Created
July 9, 2015 16:42
-
-
Save simplelife7/92d5b3e6307879292e96 to your computer and use it in GitHub Desktop.
【JS】遍历JSON所有节点
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
//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