Get an Object's Value by Index using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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

If you try to access the array at an index that's out of bounds, you'll get an undefined value back.

index.js
const obj = {country: 'Chile', name: 'Tom'}; console.log(Object.values(obj)); // 👉️ ['Chile', 'Tom'] console.log(Object.values(obj)[100]); // 👉️ undefined

A more indirect approach is to use the Object.keys method.

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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.