Iteration
Unlike an array or a string, an object is not an iterable entity, so it cannot
be iterated over with for
or for...of
loops.
for...in
loop
To iterate over objects, a special for...in
loop should be used, which
iterates over the keys of object
.
for (key in object) {
// statements
}
The variable key
is available only in the loop body. At each iteration, the
key (name) value of the property will be written to it. To get the value of a
property with such a key (name), use the syntax of square brackets.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
for (const key in book) {
// Key
console.log(key);
// The property value with this key
console.log(book[key]);
}
hasOwnProperty()
method
Let's analyze the concept of own and inherited properties of an object and learn
how to use the for...in
loop.
const animal = {
legs: 4,
};
const dog = Object.create(animal);
dog.name = "Mango";
console.log(dog); // {name: 'Mango'}
console.log(dog.name); // 'Mango'
console.log(dog.legs); // 4
The Object.create(animal)
method creates and returns a new object, linking it
to the animal
object. Therefore, you can get the value of the legs
property
by accessing it as dog.legs
, even though it does not exist in the dog
object. This is an inherited property from the animal
object.
The in
statement used in the for...in
loop does not distinguish between own
and inherited properties of an object. Not very convenient, since we always want
to iterate over only own properties. To find out whether an object has its own
property or not, use the hasOwnProperty(key)
method, which returns true
or
false
.
// ❌ Returns true for all properties
console.log("name" in dog); // true
console.log("legs" in dog); // true
// ✅ Returns true only for own properties
console.log(dog.hasOwnProperty("name")); // true
console.log(dog.hasOwnProperty("legs")); // false
Therefore, when iterating over with the for...in
loop, add own property check
at each iteration. Even if you know for sure that the object has no inherited
properties, this will protect you against mistakes in the future.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
for (const key in book) {
// If this property is own, execute the if body
if (book.hasOwnProperty(key)) {
console.log(key);
console.log(book[key]);
}
// If this is an inherited property, do nothing
}
Object.keys()
method
The built-in Object
class has several helpful methods for working with
objects. The first is Object.keys(obj)
. It returns an array of own property
keys of an object. If the object has no properties, the method will return an
empty array.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
const keys = Object.keys(book);
console.log(keys); // ['title', 'author', 'genres', 'rating']
By combining the result of Object.keys()
and the for...of
loop, you can
easily iterate over the object's own properties without using the archaic
for...in
loop with property ownership checks.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
rating: 8.38,
};
const keys = Object.keys(book);
for (const key of keys) {
// Key
console.log(key);
// Property value
console.log(book[key]);
}
You iterate over the array of object keys and at each iteration get the value of the property with such a key.
Object.values()
method
If the Object.keys(obj)
method returns an array of the object's own property
keys, the Object.values(obj)
method returns an array of its own property
values. If the object has no properties, the Object.values(obj)
method will
return an empty array.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
rating: 8.38,
};
const keys = Object.keys(book);
console.log(keys); // ['title', 'author', 'rating']
const values = Object.values(book);
console.log(values); // ['The Last Kingdom', 'Bernard Cornwell', 8.38]
The array of property values can also be iterated over with the for...of
loop,
for example, to get the total sum of numeric values.
Let's say you want to calculate the total number of products in an object using
the product-name: quantity
format. Then the Object.values()
method will help
you get an array of all values and conveniently add them up.
const goods = {
apples: 6,
grapes: 3,
bread: 4,
cheese: 7,
};
const values = Object.values(goods); // [6, 3, 4, 7]
let total = 0;
for (const value of values) {
total += value;
}
console.log(total); // 20
Object.entries()
method
The Object.entries(obj)
method returns an array, with each element as another
array of 2 elements: the property name and the value of this property from the
obj
object.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
rating: 8.38,
};
const keys = Object.keys(book);
console.log(keys); // ['title', 'author', 'rating']
const values = Object.values(book);
console.log(values); // ['The Last Kingdom', 'Bernard Cornwell', 8.38]
const entries = Object.entries(book);
console.log(entries);
// [["title", "The Last Kingdom"], ["author", "Bernard Cornwell"], ["rating", 8.38]]
In practice, the Object.entries(obj)
method is used rarely, only for some very
specific tasks. In 99% of cases, the Object.keys()
or Object.values()
method
will be used.