204

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.

14 Answers 14

333

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) { ... }
4
  • 24
    Cleary the best option unless stone age backword compatibility is required. Mar 18, 2014 at 9:01
  • 3
    Just to clarify, according to en.wikipedia.org/wiki/JavaScript#Version_history JS 1.8.5 isn't supported pre IE9. Unfortunately many people are still in the stone age.
    – Noremac
    Dec 15, 2014 at 16:48
  • if someone is using IE9 😏 i feel his pain. thanks this is amazing
    – CMS
    Jun 16, 2017 at 9:00
  • This solution also comes pretty handy when you are using objects as Key,Value dictionaries and you need to pick the first key available in the set (if any) and you don't care about order.
    – Kyordhel
    Nov 22, 2017 at 21:02
205

If you want something concise try:

for (first in obj) break;

alert(first);

wrapped as a function:

function first(obj) {
    for (var a in obj) return a;
}
4
  • 8
    See Luke Schafer's answer below, it uses the hasOwnProperty method to ensure you don't grab prototype members. Aug 1, 2011 at 17:57
  • 3
    For a one liner to work in all browsers including IE8 and below use for (var key in obj) if (obj.hasOwnProperty(key)) break; You'll then want to use the key variable
    – Ally
    Sep 6, 2013 at 16:23
  • doesn't work if the first element is an object type. returns 0
    – snow
    Aug 9, 2018 at 11:14
  • 1
    Object.keys(obj)[0]; is much faster ( 0.072ms ) than for ( 1.644ms ). Sep 26, 2018 at 23:35
77

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];
        break;
    }
}

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

2
  • There is an error in the above code. The typeof check should be typeof(i)
    – jacob.toye
    Feb 20, 2012 at 0:25
  • @Napalm he was referring to the error in the variable name being checked, not the syntax. You're right, but many people like the bracketing for readability Dec 14, 2012 at 0:12
76

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

myObject[Object.keys(myObject)[0]]
62

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.

7
  • 6
    I've never seen for(i in obj) do things in a different order, are you saying that sometimes for(i in obj) will kick things out in a different order? May 26, 2009 at 5:26
  • 4
    It's is possible that it will. The specs says that it does not have to be enumerated in a specific order. This pretty much means that that order may change. May 26, 2009 at 5:28
  • 5
    Most browsers these days do preserve insertion order, but that wasn't always the case; it's not required by the spec, and there were recent versions of Chrome that didn't preserve the insertion order.
    – Miles
    May 26, 2009 at 5:42
  • 1
    As I got deeper into what I was doing the order of things got more important (I thought I only cared about the first, but I was wrong!) so it was clear to store my objects in an array as you've suggested. May 27, 2009 at 23:02
  • 1
    If you know that the object has only one element, then you do know the order.
    – danorton
    Sep 24, 2010 at 6:44
40

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
18

There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:

var keys = ["foo", "bar", "baz"];

Then use that to get the proper value:

object[keys[0]]
17

ES6

const [first] = Object.keys(obj)
2
  • It works, but can you please explain how this works? Just showing the code fails to make me understand it.
    – Daan
    Dec 7, 2018 at 13:43
  • 1
    It's a destructuring assignment. Essentially, it assigns the first element of the returned array to the variable within the square brackets. Dec 9, 2018 at 14:58
12

Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:

_.pairs(obj)[0]

Then the key would be available with a further [0] subscript, the value with [1]

0
10

I had the same problem yesterday. I solved it like this:

var obj = {
        foo:{},
        bar:{},
        baz:{}
    },
   first = null,
   key = null;
for (var key in obj) {
    first = obj[key];
    if(typeof(first) !== 'function') {
        break;
    }
}
// first is the first enumerated property, and key it's corresponding key.

Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.

1
  • 1
    Hi @PatrikAkerstrand early I've accidentally clicked in downvote. Please make any change in your anwser to I undo it. Sorry. Dec 2, 2016 at 16:50
7

You could do something like this:

var object = {
    foo:{a:'first'},
    bar:{},
    baz:{}
}


function getAttributeByIndex(obj, index){
  var i = 0;
  for (var attr in obj){
    if (index === i){
      return obj[attr];
    }
    i++;
  }
  return null;
}


var first = getAttributeByIndex(object, 0); // returns the value of the
                                            // first (0 index) attribute
                                            // of the object ( {a:'first'} )
0
6

To get the first key of your object

const myObject = {
   'foo1': { name: 'myNam1' },
   'foo2': { name: 'myNam2' }
}

const result = Object.keys(myObject)[0];

// result will return 'foo1'
2
  • What's the difference of this answer to the Jacob's one?
    – YakovL
    Mar 8, 2017 at 15:35
  • it gives confident to the fresher that this kind of code works perfectly.
    – Santosh
    Jun 3, 2017 at 10:24
5

Based on CMS answer. I don't get the value directly, instead I take the key at its index and use this to get the value:

Object.keyAt = function(obj, index) {
    var i = 0;
    for (var key in obj) {
        if ((index || 0) === i++) return key;
    }
};


var obj = {
    foo: '1st',
    bar: '2nd',
    baz: '3rd'
};

var key = Object.keyAt(obj, 1);
var val = obj[key];

console.log(key); // => 'bar'
console.log(val); // => '2nd'
2

My solution:

Object.prototype.__index = function(index)
{
    var i = -1;
    for (var key in this)
    {
        if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
            ++i;
        if (i >= index)
            return this[key];
    }
    return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));
2
  • 12
    nice one, only… your coding style! what the hell? those braces are everywhere! Jun 25, 2012 at 13:33
  • 2
    Do you know python style? I just added vertical-aligned braces into python style. Anyway, "Hell is other people", :-D
    – diyism
    Jun 28, 2012 at 4:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.