Getting the first index of an object

Ryan Florence picture Ryan Florence · May 26, 2009 · Viewed 378.1k times · Source

Consider:

var object = {
  foo: {},
  bar: {},
  baz: {}
}

How would I do this:

var first = object[0];
console.log(first);

Obviously, that doesn’t work because the first index is named foo, not 0.

console.log(object['foo']);

works, but I don’t know it’s named foo. It could be named anything. I just want the first.

Answer

Jacob picture Jacob · Jul 10, 2013

Just for fun this works in JS 1.8.5

var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"

This matches the same order that you would see doing

for (o in obj) { ... }