694

Is there an elegant way to access the first property of an object...

  1. where you don't know the name of your properties
  2. without using a loop like for .. in or jQuery's $.each

For example, I need to access foo1 object without knowing the name of foo1:

var example = {
    foo1: { /* stuff1 */},
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};
Michael Durrant
  • 84,444
  • 83
  • 284
  • 429
atogle
  • 9,263
  • 4
  • 18
  • 13

20 Answers20

1551
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Using this you can access also other properties by indexes. Be aware tho! Object.keys return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.

Daniel Sokolowski
  • 10,545
  • 3
  • 61
  • 49
Grzegorz Kaczan
  • 17,728
  • 3
  • 16
  • 17
  • 27
    You say that it's not the fastest way. What way would be faster? – T Nguyen Sep 06 '13 at 14:19
  • 6
    This is not very efficient as it creates an entire array of all of the object's keys. – Andrew Mao Jan 29 '14 at 05:23
  • 9
    @T Nguyen I would post it if i knew it :) – Grzegorz Kaczan Feb 04 '14 at 21:13
  • This works PERFECT for me as I am trying to use both 'keys' on the same string ... element.append(''); THIS should be the answer! – Todd Vance Mar 02 '14 at 16:02
  • This works for the example, but I think the order of keys isn't entirely well defined. That might be a gotcha for some code. – fet Oct 09 '14 at 17:31
  • `for(var i in obj){ console.log(i); break; }` is two times faster that above code, as seen at [http://jsben.ch/#/AUPq5](http://jsben.ch/#/AUPq5) – DavChana Oct 30 '16 at 20:51
  • 6
    @DavChana - You had your benchmark set up wrong. The *boilerplate block* will always be executed and your *block 2* was empty, meaning the first result represents execution *boilerplate+block1*, and the second result represents only *boilerplate*. __Here is the correct benchmark: [http://jsben.ch/#/R9aLQ](http://jsben.ch/#/R9aLQ)__, showing they are pretty much equal (run the test multiple times). – myfunkyside Nov 12 '16 at 14:06
  • 17
    I wish `first()` or something similar could handle this. – Fr0zenFyr Dec 06 '16 at 07:18
  • As others have said, not ideal for every case but great for a simple one-liner. To avoid a speed hit you can cache the key array before loops, etc. `var k = Object.keys(obj); for(...){foo = obj[k[i]];}`. Then again that's just a clunky way of using `for...in`. – Beejor Aug 19 '18 at 01:44
  • This is returning the value and he is asking for the first key name in the object. – Diego Unanue Jun 12 '19 at 17:32
  • Shameless plug for shorter version https://stackoverflow.com/a/42450925/3599414 – garrettmaring Apr 20 '21 at 21:43
131

Try the for … in loop and break after the first iteration:

for (var prop in object) {
    // object[prop]
    break;
}
Gumbo
  • 594,236
  • 102
  • 740
  • 814
  • 1
    I think this is about the only option. I'm not sure you're guaranteed that the properties will be iterated in a predictable/useful order though. I.e., you may intend foo1 but get foo3. If the properties are numbered as in the example, you could do a string compare to ascertain the identifier ending in '1'. Then again, if ordinality is the main concern of the collection, you should probably use an array instead of an object. – steamer25 Jun 11 '09 at 20:13
  • 2
    If anyone else is concerned about the order, most browsers behave predictably: http://stackoverflow.com/questions/280713/elements-order-in-a-for-in-loop – Flash Feb 04 '13 at 05:39
  • 8
    var prop; for (prop in object) break; //object[prop] – netiul Jun 05 '14 at 13:16
  • 13
    Old answer but. You might want to check if the property belongs to the object. like: for(..){ if(!obj.hasOwnProperty(prop)) continue; .... break; } just in case the object is actually empty it does not traverses the prototype or something. – pgarciacamou Sep 12 '14 at 21:24
99

You can also do Object.values(example)[0].

garrettmaring
  • 4,580
  • 2
  • 20
  • 39
  • 1
    This is not available in all browsers, referencing https://stackoverflow.com/a/38748490/719689 – AlxVallejo Jul 05 '17 at 21:04
  • 3
    I like this better than `Object.keys`, because you are guaranteed to get the first item. – theUtherSide May 16 '18 at 22:13
  • 2
    Update from 2019, I think that this works on most browsers except for IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values – ppak10 Nov 27 '19 at 02:46
48

Use Object.keys to get an array of the properties on an object. Example:

var example = {
    foo1: { /* stuff1 */},
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

var keys = Object.keys(example); // => ["foo1", "foo2", "foo3"] (Note: the order here is not reliable)

Documentation and cross-browser shim provided here. An example of its use can be found in another one of my answers here.

Edit: for clarity, I just want to echo what was correctly stated in other answers: the key order in javascript objects is undefined.

Community
  • 1
  • 1
benekastah
  • 5,421
  • 1
  • 31
  • 46
25

A one-rule version:

var val = example[function() { for (var k in example) return k }()];
Nathan Arthur
  • 5,424
  • 3
  • 42
  • 64
netiul
  • 2,639
  • 2
  • 21
  • 29
  • 2
    Sometimes it can be risky to use `for in` without checking `hasOwnProperty` as the object contain other unwanted values appended to it programmatically so you could end up getting an unwanted result from this snippet. Just because its short and neat doesn't mean its safe optimal. – Javier Cobos Jul 11 '18 at 06:37
24

There isn't a "first" property. Object keys are unordered.

If you loop over them with for (var foo in bar) you will get them in some order, but it may change in future (especially if you add or remove other keys).

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
12

Solution with lodash library:

_.find(example) // => {name: "foo1"}

but there is no guarantee of the object properties internal storage order because it depends on javascript VM implementation.

pocheptsov
  • 1,846
  • 22
  • 23
  • 2
    Just tested this, and it doesn't work. It returns the value only, not the key/value pair. – Chris Haines Sep 18 '17 at 12:40
  • 2
    There is no mention in the question that it should return the key/value pair, he just asks for the object and the accepted answer does just as much as this lodash function: it returns the content of the first property. It might not suit your specific needs, but this answer IS correct based on the original question. – Carrm Nov 30 '18 at 10:10
  • Yes does the job, useful when you know your object will have only one child object `var object = { childIndex: { .. } }; var childObject = _.find(Object);` – Raja Khoury Apr 12 '19 at 20:11
11

The top answer could generate the whole array and then capture from the list. Here is an another effective shortcut

var obj = { first: 'someVal' };
Object.entries(obj)[0][1] // someVal
kishorekumaru
  • 1,116
  • 1
  • 15
  • 25
8

No. An object literal, as defined by MDC is:

a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Therefore an object literal is not an array, and you can only access the properties using their explicit name or a for loop using the in keyword.

Alex Rozanski
  • 37,325
  • 9
  • 65
  • 69
  • 26
    For others only seeing the green tick on this answer, there is another solution further down the page with currently 350 upvotes. – redfox05 Nov 13 '15 at 10:12
7

Here is a cleaner way of getting the first key:

var object = {
    foo1: 'value of the first property "foo1"',
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

let [firstKey] = Object.keys(object)

console.log(firstKey)
console.log(object[firstKey])
Ntiyiso Rikhotso
  • 419
  • 3
  • 10
  • But why the array around `[first]`. User did not request an array as the answer. Why do this over `first = Object.keys(example)[0]` which will do the same without needing to wrap the answer in an array. Why is yours cleaner please? – Michael Durrant Apr 27 '20 at 11:46
  • That is a destructuring assignment https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Ntiyiso Rikhotso Apr 28 '20 at 07:44
4

To get the first key name in the object you can use:

var obj = { first: 'someVal' };
Object.keys(obj)[0]; //returns 'first'

Returns a string, so you cant access nested objects if there were, like:

var obj = { first: { someVal : { id : 1} }; Here with that solution you can't access id.

The best solution if you want to get the actual object is using lodash like:

obj[_.first(_.keys(obj))].id

To return the value of the first key, (if you don't know exactly the first key name):

var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

if you know the key name just use:

obj.first

or

obj['first']
Diego Unanue
  • 5,488
  • 5
  • 39
  • 62
3

I don't recommend you to use Object.keys since its not supported in old IE versions. But if you really need that, you could use the code above to guarantee the back compatibility:

if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
    hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
    dontEnums = [
      'toString',
      'toLocaleString',
      'valueOf',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'constructor'
    ],
    dontEnumsLength = dontEnums.length;

return function (obj) {
  if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

  var result = [];

  for (var prop in obj) {
    if (hasOwnProperty.call(obj, prop)) result.push(prop);
  }

  if (hasDontEnumBug) {
    for (var i=0; i < dontEnumsLength; i++) {
      if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
    }
  }
  return result;
}})()};

Feature Firefox (Gecko)4 (2.0) Chrome 5 Internet Explorer 9 Opera 12 Safari 5

More info: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys

But if you only need the first one, we could arrange a shorter solution like:

var data = {"key1":"123","key2":"456"};
var first = {};
for(key in data){
    if(data.hasOwnProperty(key)){
        first.key = key;
        first.content =  data[key];
        break;
    }
}
console.log(first); // {key:"key",content:"123"}
Javier Cobos
  • 1,063
  • 10
  • 17
3

This has been covered here before.

The concept of first does not apply to object properties, and the order of a for...in loop is not guaranteed by the specs, however in practice it is reliably FIFO except critically for chrome (bug report). Make your decisions accordingly.

annakata
  • 70,224
  • 16
  • 111
  • 179
2

if someone prefers array destructuring

const [firstKey] = Object.keys(object);
Željko Šević
  • 1,608
  • 1
  • 12
  • 17
1

we can also do with this approch.

var example = {
  foo1: { /* stuff1 */},
  foo2: { /* stuff2 */},
  foo3: { /* stuff3 */}
}; 
Object.entries(example)[0][1];
Salil Sharma
  • 359
  • 4
  • 13
1

You can use Object.values() to access values of an object:

var obj = { first: 'someVal' };
Object.values(obj)[0]; // someVal
0

Any reason not to do this?

> example.map(x => x.name);

(3) ["foo1", "foo2", "foo3"]
jtr13
  • 996
  • 8
  • 19
  • 9
    Because `.map()` only exists for [built-in iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Built-in_iterables) – kano Apr 27 '18 at 10:58
0

You can use Object.prototype.keys which returns all the keys of an object in the same order. So if you want the first object just get that array and use the first element as desired key.

const o = { "key1": "value1", "key2": "value2"};
const idx = 0; // add the index for which you want value
var key = Object.keys(o)[idx];
value = o[key]
console.log(key,value); // key2 value2
adiga
  • 28,937
  • 7
  • 45
  • 66
  • 1
    When answering an old question, your answer would be much more useful to other StackOverflow users if you included some context to explain how your answer helps, particularly for a question that already has an accepted answer. See: [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – David Buck Dec 02 '19 at 12:30
0

If you need to access "the first property of an object", it might mean that there is something wrong with your logic. The order of an object's properties should not matter.

Flavius Stef
  • 13,206
  • 2
  • 24
  • 22
  • You're right. I don't need the first one, per se, but just one of the foo properties so I can work with it. I only need one and wasn't sure if there was a way just to grab the "first" one without using for ... in. – atogle Jun 11 '09 at 20:15
-1

As others have pointed out, if the order of properties is important, storing them in an object is not a good idea. Instead, you should use an array via square brackets. E.g.,

var example = [ {/* stuff1 */}, { /* stuff2 */}, { /* stuff3 */}];
var first = example[0];

Note that you lose the 'foo' identifiers. But you could add a name property to the contained objects:

var example = [ 
  {name: 'foo1', /* stuff1 */},
  {name: 'foo2', /* stuff2 */},
  {name: 'foo3', /* stuff3 */}
];
var whatWasFirst = example[0].name;

For those seeking an answer to a similar question, namely: "How do I find one or more properties that match a certain pattern?", I'd recommend using Object.keys(). To extend benekastah's answer:

for (const propName of Object.keys(example)) {
  if (propName.startsWith('foo')) {
    console.log(`Found propName ${propName} with value ${example[propName]}`);
    break;
  }
}
steamer25
  • 8,343
  • 1
  • 28
  • 37
  • there are situations in which we can't. We're assuming we can't change the fact that they're not in an array – 1mike12 Jul 31 '16 at 19:33
  • 1
    I think it's useful to push back on the design a bit for readers who can control their JSON schema. Essentially, I'm extending Flavius Stef's answer with some examples. – steamer25 Aug 15 '16 at 19:36