Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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]
.
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.
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.
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.
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]
.
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.
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.