Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Loop and Enumerate Object Keys with Object.

keys()
The Object.keys() method was added in ES6 to make looping over objects easier. It generates
an array whose elements are strings containing the names (keys) of an object's properties. The
object is passed as an argument to Object.keys(). After that, you can iterate through the array
and retrieve the value of each property using any of the array looping methods, such
as forEach(), map(), etc.
Object.keys(objectName);

For example, suppose we have an object of user scores in various subjects:


const userScores = {
chemistry: 60,
mathematics: 70,
physics: 80,
english: 98
};

We can loop through the object and fetch the keys, which for this example would be the subjects:
const names = Object.keys(userScores);
console.log(names); // ["chemistry","mathematics","physics","english"]

You will notice that this returned an array, which we can now make use of any array method to
retrieve the data:
names.forEach((key, index) => {
console.log(`${index}: ${key}`);
});

This results in:


0: chemistry
1: mathematics
2: physics
3: english

It's worth noting that you can also get the value using this notation - by supplying the key to the
object:
names.forEach((key, index) => {
console.log(`${index} - Key: ${key}, Value: ${userScores[key]}`);
});

0 - Key: chemistry, Value: 60


1 - Key: mathematics, Value: 70
2 - Key: physics, Value: 80
3 - Key: english, Value: 98

You might also like