Is there a way to get the name of the first property of a JSON object?
I'd like to do something like this:
var firstProp = jsonObj[0];
edit: I'm getting a JSON object which hold categories of arrays with image URLs.
like so:
{ "category1":["image/url/1.jpg","image/url/2.jpg"], "category2":["image/url/3.jpg","image/url/4.jpg"] }
I am then iterating through the object to insert the images, and all I really wanted was an elegant way to see which category was inserted first. At first I just did
for (var cat in images) { if (i==0) firstCat = cat; ... }
But that some how "felt" ugly... So it was basically just a question of elegance.
Make any Object array ( req ), then simply do Object. keys(req)[0] to pick the first key in the Object array.
Any error or exception? The JSON RFC (RFC 4627) says that order of object members does not matter.
console.log(jsonObj[Object.keys(jsonObj)[0]]);
The order of the properties of an object are not guaranteed to be the same as the way you put them in. In practice, however, all major browsers do return them in order. So if you're okay with relying on this...
var firstProp; for(var key in jsonObj) { if(jsonObj.hasOwnProperty(key)) { firstProp = jsonObj[key]; break; } }
Also note that there's a bug in Chrome regarding the ordering, in some edge cases it doesn't order it in the way they were provided. As far as it changing in the future, the chances are actually pretty small as I believe this is becoming part of the standard so if anything support for this will only become official.
All things considered, though, if you really, really, absolutely, positively, want to be sure it's going to be in the right order you need to use an array. Otherwise, the above is fine.
Related question: Elements order - for (… in …) loop in javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With