Iterating Through an Object with `forEach()`
JavaScript's Array#forEach()
function lets you iterate over
an array,
but not over an object. But you can iterate over a JavaScript object using forEach()
if you transform the object into an array first, using Object.keys()
, Object.values()
, or Object.entries()
.
Using Object.keys()
The Object.keys()
function returns an array of the object's own enumerable
properties. You can then iterate over each key in the object using forEach()
.
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
Using Object.values()
The Object.values()
function returns an array of the object's own enumerable
property values. In other words, it returns an array over the object's values
that you can iterate through using forEach()
.
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "Jean-Luc Picard" followed by "Captain"
Object.values(obj).forEach(val => {
console.log(val);
});
Using Object.entries()
The Object.entries()
function returns an array of entries. An entry is
an array of length 2, where entry[0]
is the key and entry[1]
is the
value. You can iterate through both keys and values simultaneously:
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.entries(obj).forEach(entry => {
const [key, value] = entry;
console.log(key, value);
});