Borislav Hadzhiev
Fri Oct 29 2021·2 min read
Photo by Kinga Cichewicz
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]
.
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.
const obj = {country: 'Chile', name: 'Tom'}; console.log(Object.values(obj)); // 👉️ ['Chile', 'Tom']
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:
Object.keys()
method to get an array of the object's keys.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.
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.