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.
Reference:
entries
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well.
JavaScript:
Object.entries(obj)
TypeScript:
entries(o: { [s: string]: T } | ArrayLike): [string, T][];
Examples:
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
keys
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
JavaScript:
Object.keys(obj)
TypeScript:
keys(o: {}): string[];
Examples:
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
values
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.
JavaScript:
Object.values(obj)
TypeScript:
values(o: { [s: string]: T } | ArrayLike): T[];
Examples:
const arrayLikeObj1 = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(arrayLikeObj1 )); // ['a', 'b', 'c']
Share "How to access the first property of an object in JavaScript?"
Related snippets:
Tags:
access, get, find, first, property, key, value, entry, object, javascript Technical term:
Access the first property of an object in JavaScript