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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Ryan Florence
  • 13,361
  • 9
  • 46
  • 63

14 Answers14

334

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) { ... }
Jacob
  • 10,452
  • 5
  • 22
  • 11
  • 24
    Cleary the best option unless stone age backword compatibility is required. – Dag Sondre Hansen Mar 18 '14 at 09:01
  • 3
    Just to clarify, according to http://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 '14 at 16:48
  • if someone is using IE9 i feel his pain. thanks this is amazing – CMS Jun 16 '17 at 09: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 '17 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;
}
yckart
  • 32,460
  • 9
  • 122
  • 129
Patrick Hayes
  • 2,099
  • 2
  • 12
  • 2
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.

aksu
  • 5,221
  • 5
  • 24
  • 39
Luke Schafer
  • 9,209
  • 2
  • 28
  • 29
  • There is an error in the above code. The typeof check should be typeof(i) – jacob.toye Feb 20 '12 at 00: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 – Luke Schafer Dec 14 '12 at 00: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]]
Rob Fox
  • 5,355
  • 7
  • 37
  • 63
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.

Miles
  • 31,360
  • 7
  • 64
  • 74
  • 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? – Ryan Florence May 26 '09 at 05: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. – PatrikAkerstrand May 26 '09 at 05: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 '09 at 05: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. – Ryan Florence May 27 '09 at 23:02
  • 1
    If you know that the object has only one element, then you do know the order. – danorton Sep 24 '10 at 06:44
  • 1
    In most normal contexts, you may be correct... However it is bad to assume this for everyone. Like if you don't have control over the object, or if there is only one item with (and you don't definitively know the name). Though in most other cases I agree. –  Apr 02 '16 at 07:21
  • Actually, the order of objects is guaranteed since ES2015 https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Daniel May 22 '20 at 14:27
39

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
jitendra varshney
  • 3,484
  • 1
  • 21
  • 31
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]]
Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
17

ES6

const [first] = Object.keys(obj)
Richard Ayotte
  • 5,021
  • 1
  • 36
  • 34
  • It works, but can you please explain how this works? Just showing the code fails to make me understand it. – Daan Dec 07 '18 at 13:43
  • 1
    It's a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). Essentially, it assigns the first element of the returned array to the variable within the square brackets. – Richard Ayotte Dec 09 '18 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]

Dexygen
  • 12,287
  • 13
  • 80
  • 147
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.

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
  • 1
    Hi @PatrikAkerstrand early I've accidentally clicked in downvote. Please make any change in your anwser to I undo it. Sorry. – rogeriolino Dec 02 '16 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'} )
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
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'
ldls
  • 159
  • 1
  • 8
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'
Community
  • 1
  • 1
yckart
  • 32,460
  • 9
  • 122
  • 129
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));
YakovL
  • 7,557
  • 12
  • 62
  • 102
diyism
  • 12,477
  • 5
  • 46
  • 46