Borislav Hadzhiev
Last updated: Oct 5, 2021
Check out my new book
To access the first property of an object, pass the object to the
Object.values
method and access the element at index 0
, e.g.
Object.values(obj)[0]
.
The Object.values
method returns an array containing all of the object's
values.
// 👉️ Not Supported in IE 6-11 const obj = {one: '1', two: '2', three: '3'}; const firstValue = Object.values(obj)[0]; // 👉️ '1' console.log(firstValue);
The
Object.values
method returns an array containing all of the object's values. In our example -
['1', '2', '3']
.
0
to get the value of the first key in the object.Note that Object.values
is not natively supported in Internet Explorer. If you
need to support the browser, add a
polyfill
for it or use babel to compile your code to an older
version of JavaScript that the browser can understand.
Alternatively, you can use the Object.keys
method, which is supported in
Internet Explorer 9-11.
// 👉️ Supported in IE 9-11 const obj = {one: '1', two: '2', three: '3'}; const firstValue = obj[Object.keys(obj)[0]]; // 👉️ '1' console.log(firstValue);
In the code snippet we used the Object.keys method to get an array of the object's keys.
const obj = {one: '1', two: '2', three: '3'}; const keys = Object.keys(obj) // 👉️ ['one', 'two', 'three'] console.log(keys)
To get the first key of the object, we access the array at index 0
.
The last step is to access the object at the first property to get the corresponding value.
const obj = {one: '1', two: '2', three: '3'}; const keys = Object.keys(obj); // 👉️ ['one', 'two', 'three'] const value = obj[keys[0]]; // 👉️ '1' console.log(value);
Object.values
approach is definitely more direct and intuitive, however if you have to support Internet Explorer and don't use babel
, the Object.keys
method gets the job done.