views:

936

answers:

3

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 wich 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 :p

+1  A: 

Great question. I don't know of any way besides iterating in a for-in loop. You only need to iterate once though. For safety, ensure it's a known property [more info].

for (var propName in jsonObj) {
    if (jsonObj.hasOwnProperty(propName)) {
        return propName;    // or do something with it and break
    }
}

Edited to be extra clear that you're iterating over the property names, not their values.

Aseem Kishore
+5  A: 
David Dorward
Good point that they're not guaranteed to be the order you specified them in -- upvoted. I would make sure to check hasOwnProperty() though.
Aseem Kishore
I'm getting a JSON object, so arrays aren't really an option...
peirix
Errrrrrrr ......... { data: [1,2,3,4] }
David Dorward
+6  A: 

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

Paolo Bergantino
But what if that changes in the future?
the_drow