In JavaScript, Object
s are not iterable unless they implement the iterable protocol. Therefore, you cannot use for...of
to iterate over the properties of an object.
const obj = { France: "Paris", England: "London" };
for (const p of obj) {
}
Instead you have to use Object.keys
or Object.entries
, to iterate over the properties or entries of an object.
const obj = { France: "Paris", England: "London" };
for (const country of Object.keys(obj)) {
const capital = obj[country];
console.log(country, capital);
}
for (const [country, capital] of Object.entries(obj)) {
console.log(country, capital);
}
Another option for this use case might be to use a Map
:
const map = new Map();
map.set("France", "Paris");
map.set("England", "London");
for (const country of map.keys()) {
const capital = map.get(country);
console.log(country, capital);
}
for (const capital of map.values()) {
console.log(capital);
}
for (const [country, capital] of map.entries()) {
console.log(country, capital);
}