Sometimes, we want to get the names of the properties in a JavaScript object.
In this article, we’ll look at how to get a JavaScript object’s property names with JavaScript.
Using the Object.keys Method
We can use the Object.keys
method to return an array of property name strings.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
}
Object.keys(obj).forEach(key => {
console.log(key)
console.log(obj[key])
})
We created the obj
object with properties a
, b
, and c
.
Then we call Object.keys
with obj
to return the property names of obj
as strings.
Then we call forEach
with a callback that has the key
parameter with the key of the object being iterated through.
In the callback, we log the key
and the value which we access with obj[key]
.
Therefore, we get:
a
1
b
2
c
3
as the result.
Using the for-in Loop
We can get the object keys with the for-in loop.
For instance, we can write:
const obj = {
a: 1,
b: 2,
c: 3
}
for (const key in obj) {
console.log(key);
console.log(obj[key]);
}
We get the object key from the key
loop variable.
And then we get the key and value within the loop body the same way.
Therefore, we get:
a
1
b
2
c
3
as the result just like the previous example.
The for-in loop also loops through any properties inherited from prototype objects so we may get more keys than from the Object.keys
method.
Object.keys
only get property keys from non-inherited properties.
Conclusion
We can use the Object.keys
method or the for-in loop to get the keys from a JavaScript object.