Skip to content

Instantly share code, notes, and snippets.

@McKabue
Created May 10, 2016 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save McKabue/a6aa13374f0997024c760101a23566d2 to your computer and use it in GitHub Desktop.
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/
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