Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to transform all values of an object

Short answer

Turn the object into pairs, change the values with map() and build a new object:

const prices = { tea: 3, coffee: 4, cake: 5 };
const doubled = Object.fromEntries(Object.entries(prices).map(([name, price]) => [name, price * 2]));
 
console.log(JSON.stringify(doubled));

Output:

{"tea":6,"coffee":8,"cake":10}

Changing keys

The same way you can change keys, for example make them uppercase:

const env = { host: 'localhost', port: 8080 };
const upper = Object.fromEntries(Object.entries(env).map(([key, value]) => [key.toUpperCase(), value]));
 
console.log(JSON.stringify(upper));

Output:

{"HOST":"localhost","PORT":8080}

Common mistake

Objects have no map() method, it belongs to arrays:

try {
  ({ a: 1 }).map((x) => x);
} catch (error) {
  console.log(error.constructor.name);
}

Output:

TypeError

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.