AI Hints
Home›JavaScript Tutorial›Working with Objects
JavaScript · Lesson 61 of 138

Looping Objects

Object.keys, entries.

⏱ 2 min read▶ Video at 1:14:36🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Objects aren't lists, so for of doesn't work on them directly. But JavaScript can give you an object's keys, values, or both, as arrays. Then you can loop, map, or filter as usual.

Looping Objects
From the video: Looping Objects
  • Objects aren't lists
  • Get keys, values, or both
  • Then loop as usual

Keys, values, and entries

Object dot keys gives an array of the keys. Object dot values gives the values. And object dot entries gives key and value pairs, which we can destructure right in the loop. Run it.

app.jsjavascript
const stock = { apples: 12, pears: 0, figs: 7 };

console.log(Object.keys(stock));
console.log(Object.values(stock));

for (const [fruit, count] of Object.entries(stock)) {
  console.log(`${fruit}: ${count > 0 ? count : "sold out"}`);
}
Output
[ 'apples', 'pears', 'figs' ]
[ 12, 0, 7 ]
apples: 12
pears: sold out
figs: 7

Turning entries back into objects

Entries are just arrays, so we can filter them. Here we keep only the fruits in stock. Then object dot from entries turns the pairs back into an object. And we can sum the values with reduce. Run it.

app.jsjavascript
const stock = { apples: 12, pears: 0, figs: 7 };

const inStock = Object.fromEntries(
  Object.entries(stock).filter(([, n]) => n > 0)
);
console.log(inStock);

const total = Object.values(stock).reduce((a, b) => a + b, 0);
console.log("Total fruit:", total);
Output
{ apples: 12, figs: 7 }
Total fruit: 19

Summary

Object dot keys, values, and entries turn an object into arrays you can loop over, and from entries turns pairs back into an object. Next, destructuring objects.

Key takeaways
  • Object.keys / values
  • Object.entries
  • Object.fromEntries
Next up: Destructuring Objects — unpacking properties