Created
May 10, 2016 12:09
-
-
Save mckabue/a6aa13374f0997024c760101a23566d2 to your computer and use it in GitHub Desktop.
This is a javascript function that traverses a JSON object however deep it is... This is important when you want to do a search on each of the elements of an object, see here https://jsfiddle.net/kyk5zf6y/
This file contains 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 o = { | |
"firstName": "John", | |
"lastName" : "doe", | |
"age" : 26, | |
"arr":[1,2,3], | |
"address" : { | |
"streetAddress": "naist street", | |
"city" : "Nara", | |
"postalCode" : "630-0192" | |
}, | |
"phoneNumbers": [ | |
{ | |
"type" : "iPhone", | |
"number": "0123-4567-8888" | |
}, | |
{ | |
"type" : "home", | |
"number": "0123-4567-8910" | |
} | |
] | |
}; | |
//called with every property and it's value | |
function process(key,value,path) { | |
var log = 'key: ' +key + ", value: "+value+", path: "+path; | |
console.log(log); | |
} | |
function traverse(o,path,func) { | |
for (var i in o) { | |
if (o[i] !== null && typeof(o[i])=="object") { | |
//going on step down in the object tree!! | |
o[i].path = path+'/'+i; | |
traverse(o[i],o[i].path,func); | |
}else if(i !== 'path'){ | |
func.apply(this,[i,o[i], path+'/'+i]); | |
} | |
} | |
} | |
//that's all... no magic, no bloated framework | |
traverse(o,'root',process); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment