How to Get the First Key Name of an Object in JavaScript
- Get the First Key Name of an Object in JavaScript
-
Use
Object.entries()
to Get the First Key Name of an Object in JavaScript -
Use
Object.keys()
to Get the First Key Name of an Object in JavaScript - Conclusion
This article will demonstrate how to extract the key of an object’s first property (key and value pair).
Get the First Key Name of an Object in JavaScript
Let’s take an example to understand this.
Here, we have created an object with three properties and stored it inside a variable obj
. We will get the first key
, i.e., foo
from this object.
const obj = {
foo: 'bar',
baz: 42,
man: true
};
To get the key
from an object, we can use methods entires
and keys()
provided by the Object class in JavaScript.
Use Object.entries()
to Get the First Key Name of an Object in JavaScript
The job of the Object.entries()
method is to take each key-value pair from the object and convert these pairs into an array and store them inside one big array. This method only takes a single argument, which is the object itself.
So, if we pass the object we created above inside this method, we will have an array as an output.
console.log(Object.entries(obj));
Output:
It becomes easy to access the first key from this array using indexing. To do this, we will use [0]
after the entries()
method to have access to the first property of the array, i.e., ['foo', 'bar']
.
There is another array with two elements, foo
and bar
, and we want to access foo
. So, we will use another [0]
for this.
This is how we can access the first key of the object using Object.entries()
in JavaScript.
Use Object.keys()
to Get the First Key Name of an Object in JavaScript
Another way to get the first key of the object in JavaScript is by using the Object.keys()
method. This method works similarly to the entries()
method, and it also returns an array.
The only difference is that the Object.keys()
method returns only the keys from an object and not the values. This method also takes a single argument, which is the object itself.
Object.keys(obj);
Now, it’s simple to get the first key from this array. We only have to access the zeroth index of the array using indexing as follows.
Conclusion
The Object.entries()
and Object.keys()
methods are used to get the first key of an object in JavaScript. Both of these methods return an array.
The Object.entries()
method returns both the keys and values, whereas the Object.keys()
method only returns the keys.
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.
LinkedIn