How to access the first property of a Javascript object?

Viewed 698516

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 */}
};
23 Answers

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

for (var prop in object) {
    // object[prop]
    break;
}

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

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

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

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

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])

No. An object literal, as defined by MDN 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.

if someone prefers array destructuring

const [firstKey] = Object.keys(object);

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']

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.

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.

A more efficient way to do this, without calling Object.keys() or Object.values() which returns an array:

Object.prototype.firstKey = function () {
  for (const k in this) {
    if (Object.prototype.hasOwnProperty.call(this, k)) return k;
  }
  return null;
};

Then you can use it like:

const obj = {a: 1, b: 2, c: 3}
console.log(obj.firstKey()) //=> 'a'

This doesn't necessarily return the first key, see Elements order in a "for (… in …)" loop

we can also do with this approch.

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

This is an old question but most of the solutions assume that we know the attribute's name which it is not the case for example if you are trying to visualize data from files that the user can upload or similar cases.

This is a simple function that I use and works in both cases that you know the variable and if not it will return the first attribute of the object (sorted alphabetically)

The label function receives an object d and extract the key if exits, otherwise returns the first attribute of the object.

const data = [
  { label: "A", value: 10 },
  { label: "B", value: 15 },
  { label: "C", value: 20 },
  { label: "D", value: 25 },
  { label: "E", value: 30 }
]

const keys = ['label', 0, '', null, undefined]

const label = (d, k) => k ? d[k] : Object.values(d)[0]

data.forEach(d => {
  console.log(`first: ${label(d)}, label: ${label(d, keys[0])}`)
})

keys.forEach(k => {
  console.log(`label of ${k}: ${label(data[0], k)}`)
})

For values like 0, '', null, and undefined will return the first element of the array.

this is my solution

  const dataToSend = {email:'king@gmail.com',password:'12345'};
   const formData = new FormData();
      for (let i = 0; i < Object.keys(dataToSend).length; i++) {
     formData.append(Object.keys(dataToSend)[i], 
         Object.values(dataToSend)[i]);
      }

  console.log(formData);

Any reason not to do this?

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

(3) ["foo1", "foo2", "foo3"]

Basic syntax to iterate through key-value gracefully

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"

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;
  }
}
Related