In this article we will learn how to loop through object keys.
It is very common to iterate over an object keys in JavaScript.
To iterate over objects keys we will use Object.keys
method.
The Object.keys() method returns an array of a given object's own enumerable string-keyed property names. (Source: MDN)
Problem
Now we want to iterate over the keys of the object.
Imagine you have an object like this:
const myObj = {
name: "John",
age: 30,
}
And we want to iterate over the keys to give us this output:
name
age
How do you solve that problem?
As we said before, we will use Object.keys
to solve this problem.
How to iterate over an object keys using Object.keys
method
It takes the object that you want to loop over as an argument and returns an array of keys.
Example
// Object
const myObject = {
name: "John",
age: 30,
}
// Keys
const keys = Object.keys(myObject);
// Print Keys
console.log(keys);
Output
[ 'name', 'age' ]
As you can see, it returned an array with all the keys, and this means that we can iterate over the array in any way.
// Object
const myObject = {
name: "John",
age: 30,
}
// Array of keys
const keys = Object.keys(myObject);
// Iterate over keys with `forEach`
keys.forEach(key => {
console.log(key);
});
Output
name
age
Thank you for reading
Thank you for reading my blog. 🚀