Get an Object's Key by Index in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20211 min read

banner

Photo by freestocks

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 to get the key.

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

If you try to get a key at an index that doesn't exist, you will get undefined back.

index.js
const obj = {number: 5, color: 'blue'}; console.log(Object.keys(obj)[100]); // ๐Ÿ‘‰๏ธ undefined

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