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
  • 16,564
  • 7
  • 51
  • 69
Ryan Florence
  • 13,229
  • 9
  • 45
  • 61

14 Answers14

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) { ... }
Jacob
  • 9,954
  • 5
  • 21
  • 11
204

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
  • 30,290
  • 9
  • 117
  • 125
Patrick Hayes
  • 2,089
  • 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,163
  • 5
  • 22
  • 38
Luke Schafer
  • 9,111
  • 2
  • 27
  • 28
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,135
  • 5
  • 34
  • 61
61

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
  • 29,954
  • 7
  • 58
  • 72
  • 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
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
jitendra varshney
  • 3,410
  • 1
  • 19
  • 27
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
  • 133,880
  • 36
  • 215
  • 235
17

ES6

const [first] = Object.keys(obj)
Richard Ayotte
  • 4,871
  • 1
  • 33
  • 33
  • 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,041
  • 11
  • 76
  • 145
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
  • 44,619
  • 11
  • 77
  • 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ó
  • 769,263
  • 179
  • 909
  • 832
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
  • 141
  • 1
  • 6
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
  • 30,290
  • 9
  • 117
  • 125
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
  • 6,451
  • 11
  • 52
  • 82
diyism
  • 11,894
  • 5
  • 45
  • 44