Get an Object's Value by Index using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

Get a Value of an Object by Index #

To get a value of an object by index, call the Object.values() method to get an array of the object's values and use bracket notation to access the value at the specific index, e.g. Object.values(obj)[1].

index.js
const obj = {country: 'Chile', name: 'Tom'}; const firstValue = Object.values(obj)[0]; // ๐Ÿ‘‰๏ธ "Chile" console.log(firstValue); const firstKey = Object.keys(obj)[0]; // ๐Ÿ‘‰๏ธ "country" console.log(firstKey);

We used the Object.values method to access the first value of an object.

The method returns an array of the object's values ordered in the same way as provided by a for...in loop.

index.js
const obj = {country: 'Chile', name: 'Tom'}; console.log(Object.values(obj)); // ๐Ÿ‘‰๏ธ ['Chile', 'Tom']
The Object.values method is not supported in Internet Explorer. If you have to support the browser, use the next approach instead.

A more indirect approach is to use the Object.keys method, which is supported by Internet Explorer versions 9-11.

To get a value of an object by index:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Use bracket notation to get the key at the specific index.
  3. Access the object by the key to get the corresponding value.
index.js
const obj = {country: 'Chile', name: 'Tom'}; const keys = Object.keys(obj); console.log(obj[keys[0]]); // ๐Ÿ‘‰๏ธ Chile

The Object.keys() method returns an array of the object's keys.

index.js
const obj = {country: 'Chile', name: 'Tom'}; console.log(Object.keys(obj)); // ๐Ÿ‘‰๏ธ ['country', 'name']

We have to get the key at the specific index and use it to get the corresponding value.

This approach is definitely a bit more indirect, however if you have to support Internet Explorer, it gets the job done.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee