Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  135] [ 4]  / answers: 1 / hits: 91264  / 15 Years ago, sun, july 12, 2009, 12:00:00

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.


More From » json

 Answers
26

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


[#99143] Tuesday, July 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaliese

Total Points: 86
Total Questions: 97
Total Answers: 107

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
annaliese questions
;