Sunday, 1 May 2016

json - How can I traverse this Javascript object?










{ 
347655082: {
album:{

title: "A",
genre: "Pop",
}
},

347655083: {

album:{
title: "B",
genre: "Rock",

}
}
}


Normally the "outside" key is the same, so I can easily target the nested objects.
In the case the "outside" key is variable which can be anything.



albums = JSON.parse(json); //parse json storing it in albums



I cannot run a foreach on albums, say "albums has not method foreach".



albums.forEach(function(album, i){


}

Answer



You can only use .forEach() on arrays. Your albums entity is an Object so you should use for ... in ...)




for (var key in albums) {
if (albums.hasOwnProperty(key)) {
// do something with albums[key]
...
}
}


For code targetting node.js or any other ES5 implementation you could probably omit the if clause - it's only needed if you've got code that has unsafely added stuff to Object.prototype.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...