Getting first JSON property

There isn't a "first" property. The properties of an object are unordered.

You can get whatever one the JS engine decides to provide first with a loop.

function maybe_first_in_object(ob) {
    for (var props in ob) {
        return prop;
    }
}

… but if the order matters, use an array not an object.


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


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.


console.log(jsonObj[Object.keys(jsonObj)[0]]);