Sometimes, we may want to get the first entry of a JavaScript object.
In this article, we’ll look at how to get the first entry of a JavaScript object.
Object.keys
We can use the Object.keys
method to return an array of object keys.
Therefore, we can use it to get the key name of the first object property.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
console.log(Object.keys(obj)[0])
We have Object.keys(obj)[0]
which returns 'a'
since it’s the first entry in obj
.
Object.values
We can use the Object.values
method to return an array of object property values.
Therefore, we can use it to get the value of the first object property.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
console.log(Object.values(obj)[0])
We have Object.values(obj)[0]
which returns 1 since it’s the value of the first entry in obj
.
Object.entries
We can use the Object.entries
method to return an array of array of key-value pairs in an object.
Therefore, we can use it to get the key-value pair of the first object property.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
console.log(Object.entries(obj)[0])
We have Object.entries(obj)[0]
which returns [“a”, 1]
since it’s the first key-value pair in obj
.
Lodash toPairs Method
The Lodash toPairs
method does the same thing as the Object.entries
.
So we can use it if Object.entries
isn’t available.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
};
console.log(_.toPairs(obj)[0])
And we get [“a”, 1]
as the result in the console log.
Conclusion
We can get the first entry of a JavaScript object with plain JavaScript or Lodash.