Get an Object's Key by Index in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Get an Object's Key by Index in JavaScript #

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

index.js
const obj = {number: 5, color: 'blue'}; const secondKey = Object.keys(obj)[1]; console.log(secondKey); // 👉️ "color"

We used the Object.keys method to get an array of the object's keys.

index.js
const obj = {number: 5, color: 'blue'}; console.log(Object.keys(obj)); // 👉️ ['number', 'color']

The only parameter the method takes is the object, for which to return the keys.

The ordering of the keys in the array is the same as provided by a for...in loop.

The last step is to access the array of keys at the specific index.

JavaScript indexes are zero-based, meaning the first element in an array has an index of 0, and the last element has an index of array.length - 1.

If you try to get a key at an index that's out of bounds, you will get an undefined value back.

index.js
const obj = {number: 5, color: 'blue'}; console.log(Object.keys(obj)[100]); // 👉️ undefined

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

index.js
const obj = {name: 'Alice', age: 30}; const firstValue = Object.values(obj)[0]; console.log(firstValue); // 👉️ "Alice"

The Object.values method returns an array of the object's values.

index.js
const obj = {name: 'Alice', age: 30}; // 👇 ['Alice', 30] console.log(Object.values(obj));

You can you bracket notation to access the value at a specific index, just like we did with the array of keys.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.