BeginnerCoder

Lesson 8 — Object.entries

Loop over an object

A for...of loop works on arrays, not on plain objects. Object.entries(obj) turns an object into an array of [key, value] pairs, which you can loop over and destructure in one go. Object.keys and Object.values give only the keys or only the values.

const stock = { pens: 4, cups: 2 };
console.log(Object.entries(stock)); // [ [ 'pens', 4 ], [ 'cups', 2 ] ]
for (const [item, qty] of Object.entries(stock)) { /* ... */ }

Why it matters: settings, scores and JSON from a server are usually objects, and you often need to go through every entry.

Want it another way?
Task

Loop over scores and log each name and points on its own line: ann 3, then bob 5.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.