Getting the first index of an object

Getting the first index of an object

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

How would I do this:
var first = object[0];

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

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


Solution 1:

If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:

    {"name":"foo", ...},
    {"name":"bar", ...},
    {"name":"baz", ...}

or maybe:

    ["foo", {}],
    ["bar", {}],
    ["baz", {}]

As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no “first” property.

Solution 2:

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) { ... }

Solution 3:

If you want something concise try:

for (first in obj) break;


wrapped as a function:

function first(obj) {
    for (var a in obj) return a;

Solution 4:

they’re not really ordered, but you can do:

var first;
for (var i in obj) {
    if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
        first = obj[i];

the .hasOwnProperty() is important to ignore prototyped objects.

Solution 5:

This will not give you the first one as javascript objects are unordered, however this is fine in some cases.


Solution 6:

for first key of object you can use

console.log(Object.keys(object)[0]);//print key's name

for value

console.log(object[Object.keys(object)[0]]);//print key's value