Skip to content
Codewilds

Lesson 22 of 34 · Objects

JavaScript Object.keys, Object.entries and JSON

medium20 XP3 min read

Objects are perfect for named data, but how do you loop over them? Arrays have for...of, map and filter, while plain objects have none of those. The trick is to turn the object into an array, work with that, and turn it back if needed.

You'll also learn JSON, the text format used to save data and send it across the internet, and how to convert between JSON and JavaScript objects.

Object.keys, Object.values and Object.entries

Three built-in functions turn an object into an array:

const stats = { str: 12, dex: 9, int: 15 };

console.log(Object.keys(stats));    // [ 'str', 'dex', 'int' ]
console.log(Object.values(stats));  // [ 12, 9, 15 ]
console.log(Object.entries(stats)); // [ [ 'str', 12 ], [ 'dex', 9 ], [ 'int', 15 ] ]

Now every array tool works. The total of all stats is a reduce over the values:

const total = Object.values(stats).reduce((sum, n) => sum + n, 0);
console.log(total); // 36

And for...of over the entries with destructuring gives you both key and value:

for (const [stat, value] of Object.entries(stats)) {
  console.log(`${stat}: ${value}`);
}

You may also see the older for (const key in obj) loop. It works, but it can include inherited properties, so Object.keys/Object.entries are the safer default.

Building objects with Object.fromEntries

Object.fromEntries is the reverse of Object.entries: it turns an array of [key, value] pairs into an object. Together they form a powerful pattern: entries → array methods → fromEntries:

const doubled = Object.fromEntries(
  Object.entries(stats).map(([stat, value]) => [stat, value * 2]),
);
console.log(doubled); // { str: 24, dex: 18, int: 30 }

Objects as lookup tables

An object can be used as a quick dictionary, counting things by name. Bracket notation with a variable key does the work:

const votes = {};
for (const choice of ["fire", "ice", "fire"]) {
  votes[choice] = (votes[choice] ?? 0) + 1;
}
console.log(votes); // { fire: 2, ice: 1 }

JSON: JavaScript Object Notation

JSON is a text format for data that looks almost exactly like JavaScript object literals. It's used by web APIs, configuration files and save games. The rules are stricter than JavaScript: keys must be in double quotes, strings use double quotes, and only plain data is allowed (no functions, no undefined).

JSON.stringify converts a value to a JSON string, and JSON.parse converts it back:

const save = { hero: "Ada", level: 7, items: ["map", "rope"] };

const json = JSON.stringify(save);
console.log(json); // {"hero":"Ada","level":7,"items":["map","rope"]}
console.log(typeof json); // string

const loaded = JSON.parse(json);
console.log(loaded.items[0]); // map

Pass extra arguments to pretty-print: JSON.stringify(save, null, 2) indents the output by two spaces.

Some things don't survive the round trip: functions and undefined values are dropped, and Date objects become strings. And JSON.parse on invalid text throws a SyntaxError, which you'll learn to handle in the error-handling lesson.

Common mistakes

  • Expecting map on an object. stats.map(...) throws a TypeError; use Object.entries(stats).map(...).
  • Forgetting that keys are strings. Object.keys({ 1: "a" }) gives [ '1' ], not [ 1 ].
  • Writing JSON by hand with single quotes. JSON.parse("{'a': 1}") fails; JSON needs double quotes.
  • Comparing JSON strings to check equality. Property order changes the string; compare the data instead.

Assignment

Write four functions:

  1. countWords(text) returns an object that maps each word (in lower case) to how many times it appears. Words are separated by spaces; ignore empty strings.
    • countWords("the cat and the hat") → { the: 2, cat: 1, and: 1, hat: 1 }
    • countWords("") → {}
  2. pricesWithTax(prices, rate) returns a new object with the same keys, where every price is multiplied by 1 + rate and rounded to 2 decimals.
    • pricesWithTax({ potion: 9.99, sword: 100 }, 0.2) → { potion: 11.99, sword: 120 }
  3. saveGame(state) returns the game state as a JSON string.
  4. loadGame(json) turns a JSON string back into an object.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 22 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.