Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.4 — Looping Over Objects
JavaScript · Example 2 of 4 ES2019+

Map and filter an object with fromEntries

[, price] skips the first item of each pair (the key). URLSearchParams gives pairs too, so fromEntries turns a query string into an object; every value is a string.

Objects aren't directly loopable with for...of, so you turn them into arrays first: Object.keys for names, Object.values for values, Object.entries for [key, value] pairs; Object.fromEntries turns pairs back into an object.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given const stock = { pens: 12, books: 0, bags: 3, rulers: 0 }, log an array of the names of items that are out of stock.

02

Write invert(obj) that swaps keys and values: invert({ a: "x", b: "y" }) returns { x: 'a', y: 'b' }.

03

Given an array of fruit names with repeats, build an object counting each fruit, then log the total number of fruits using Object.values.

Explain it without notes

01

Why can't you use for...of directly on a plain object, and what do you use instead?

02

What do Object.keys, Object.values and Object.entries return, and what do they leave out?

03

How do you filter or transform an object's properties?

04

What's the difference between for...in and Object.keys?

Map and filter an object with fromEntries ES2019+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

{ tea: 25, samosa: 10, juice: 45, cake: 75 }
{ tea: 30, samosa: 15 }
{ name: 'Asha', age: '14' }