Professional Documents
Culture Documents
Looping With Object Properties With Object - Entries
Looping With Object Properties With Object - Entries
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);
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}`);
});
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]}`);
});