Object.entries, fromEntries & immutability

Reshape objects

Lesson 6 of 20 · 10 min · Module 2: Work with collections

API responses and settings often need small reshaping: keep a few fields, convert every value, or rename keys. Converting an object to entries makes array tools available for objects.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Turn objects into entries and back
  • Transform keys and values
  • Return new objects instead of changing inputs

The idea

Object.entries(obj) returns [key, value] pairs. After map or filter, Object.fromEntries(pairs) builds a new object. The original object stays unchanged.

const prices = { tea: 2, cake: 4 };
const doubled = Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, v * 2]));
console.log(doubled);

01Entries are arrays

Object.entries({a: 1}) is [["a", 1]]. Once you have an array, map, filter, sort and reduce all apply, and destructuring ([key, value]) keeps the code readable.

02Allow-lists are safer

pick(user, ["id", "name"]) copies only fields you chose. Sending a whole user object to a page or an API risks leaking a field such as password.

const user = { id: 1, name: "Ana", password: "x" };
const { password, ...safe } = user;
console.log(safe);
Output
{"id":1,"name":"Ana"}

03Own properties only

Every object inherits keys like toString. Object.hasOwn(obj, key) is true only for keys stored on the object itself, so pick never copies inherited functions.

Your turn

Write mapValues(obj, fn) that returns a new object with fn(value, key) for every value. Write pick(obj, keys) that returns a new object with only the listed keys that exist in obj. Neither function may change its input.

What the checks look for

  • mapValues transforms every value and passes the key
  • mapValues does not change the input
  • pick keeps only existing listed keys
  • pick keeps falsy values and ignores inherited keys
Try it in the editor →

Take this with you

Entries turn object reshaping into array work.

Go a little further

Write omit(obj, keys), the opposite of pick, and use it to remove secrets before logging an object.

Learn JavaScript Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →