Looping over objects
Visit every key of an object
- An object has no index
0, 1, 2, so a plainforloop cannot walk through it. for (const key in obj)gives you each key in turn.- Read the value with square brackets:
obj[key]. The dot form,obj.key, would look for a key literally called "key".
const stock = { apples: 4, pears: 0, plums: 7 };
for (const fruit in stock) {
console.log(fruit, stock[fruit]);
}
// → apples 4
// → pears 0
// → plums 7
Keys, values and entries as arrays
Object.keys(obj)gives an array of the keys.Object.values(obj)gives an array of the values.Object.entries(obj)gives an array of[key, value]pairs. You can loop over it withfor…of.
const stock = { apples: 4, pears: 0, plums: 7 };
console.log(Object.keys(stock)); // → ["apples","pears","plums"]
console.log(Object.values(stock).length); // → 3
for (const [fruit, count] of Object.entries(stock)) {
if (count === 0) {
console.log(fruit + " sold out");
}
}
// → pears sold out
Worked example: total and best
Question: an object holds each student's score. Find the total, and the name with the highest score.
const scores = { Ada: 82, Ben: 95, Cy: 77 };
let total = 0;
let best = "";
for (const name in scores) {
total += scores[name];
if (best === "" || scores[name] > scores[best]) {
best = name;
}
}
console.log(total); // → 254
console.log(best); // → Ben
The loop keeps the name of the best student, not just the score, because the score alone would not tell you who it belongs to.
Watch out
for…inis for objects. On an array, usefor…of, which gives the values.Object.keys(obj).lengthcounts the keys. An object has no.lengthof its own.
Common mistakes
- Writing
stock.fruitinside the loop. It looks for a key namedfruitand givesundefined. Usestock[fruit]. - Using
for…ofdirectly on an object. It throws "stock is not iterable". Loop overObject.entries(stock)instead. - Starting
bestat0when it should hold a name. Start from""or from the first key.
Now you try
- Loop over an object's keys, then add up its values.
- Press Check answer to test it.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
const pet = { name: "Rex", age: 3 }. Use for…in to log each key and its value, separated by a space (name Rex, then age 3).
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Write totalItems(cart), which adds up every value in an object such as { pens: 3, books: 2 } (that one gives 5). An empty object gives 0.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Write soldOut(stock), which returns an array of the keys whose value is 0, in the object's order. soldOut({ apples: 4, pears: 0, figs: 0 }) gives ["pears", "figs"].
출력을 보려면 '실행'을 클릭하세요.