Introduction
Iterating over objects helps you look at each piece of information stored inside, one by one.
for (const key in object) { // use object[key] here }
const person = {name: 'Anna', age: 25}; for (const key in person) { console.log(key + ': ' + person[key]); }
const settings = {darkMode: true, fontSize: 14}; for (const key in settings) { if (settings[key]) { console.log(key + ' is enabled'); } }
const scores = {alice: 10, bob: 15}; const keys = Object.keys(scores); for (const key of keys) { console.log(key + ' scored ' + scores[key]); }
const car = { make: 'Toyota', model: 'Corolla', year: 2020 }; for (const key in car) { console.log(`${key}: ${car[key]}`); }
obj?for...in loop is designed to iterate over all enumerable keys in an object.for...in correctly. for (let i = 0; i < obj.length; i++) { console.log(obj[i]); } tries to use a numeric index on an object, which doesn't work. for (let key of obj) { console.log(key); } uses for...of which works on iterable objects like arrays, not plain objects. obj.forEach(key => console.log(key)); tries to use forEach on an object, which is invalid.for...in loop over object data?for...in loop, key is a string representing the property name. To get the value, use bracket notation: data[key].key.value, but key is a string, not an object. for (let key in data) { console.log(data->key); } uses invalid syntax.const obj = {a: 1, b: 2, c: 3};
let result = [];
for (let key in obj) {
result.push(key + obj[key]);
}
console.log(result);const user = {name: 'Alice', age: 25};
for (let key of user) {
console.log(key + ': ' + user[key]);
}for...of works on iterable objects like arrays or strings. Plain objects are not iterable, so this causes a TypeError.key is declared correctly. String concatenation and accessing user[key] are valid if the loop worked.const scores = {alice: 10, bob: 0, carol: 5, dave: null};, which code snippet correctly creates a new object with only keys having truthy values?for...in loop and checks scores[key] truthiness correctly, adding to filtered. const filtered = {};
for (let key in scores) {
if (scores.key) filtered.key = scores.key;
} incorrectly uses dot notation with variable key. const filtered = Object.keys(scores).filter(k => scores[k]).reduce((obj, k) => { obj[k] = scores[k]; return obj; }, {}); tries to use Object.keys() with filter and reduce, but the code is missing a return statement in the arrow function (syntax error). const filtered = Object.values(scores).filter(v => v); filters values only, losing keys and returning an array, not an object.Pass the test and this pattern moves unknown