Access the First Property of an Object in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

banner

Photo by Andrew Ridley

Access the First Property of an Object in JavaScript #

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.

index.js
// ๐Ÿ‘‰๏ธ 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'].

Then we access the element at index 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.

index.js
// ๐Ÿ‘‰๏ธ 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.

index.js
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.

index.js
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);
The Object.values approach is definitely more direct and intuitive, however if you have to support Internet Explorer and don't use babel, the Object.keysmethod gets the job done.

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