- Instant help with your JavaScript coding problems

Access the first property of an object in JavaScript

Question:
How to access the first property of an object in JavaScript?
Answer:
const user = {
	name: 'John',
	city: 'Boston',
	birth_year: 1989,
	birth_place: 'London'
}

const firstEntry = Object.entries(user)[0];
const firstKey = Object.keys(user)[0];
const firstValue = Object.values(user)[0];

console.log('Firts entry: ', firstEntry);  // 0: 'name', 1: 'John'
console.log('Firts key: ', firstKey);      // name
console.log('Firts value: ', firstValue);  // John
Description:

If you want to access the first property of a JavaScript object, you first need to specify your needs. What exactly do you need? The name of the property, its value, or both?

Fortunately, each of these cases can be easily accessed using the built-in Object class. You can use different methods for the above cases:

  • The Object.entries() method returns an array of a given object's own key-value pairs.
  • The Object.keys() method returns an array of a given object's own property names.
  • The Object.values() method returns an array of a given object's own property values.

Once you have the right array, you can easily access the first element of it at index 0.

 

Share "How to access the first property of an object in JavaScript?"
Tags:
access, get, find, first, property, key, value, entry, object, javascript
Technical term:
Access the first property of an object in JavaScript