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:
TypeErrorFunctions used in this recipe
- Object.entries — Returns an array of property name and value pairs.
- Object.fromEntries — Creates an object from a list of key–value pairs.
- Array.prototype.map — Creates a new array by transforming every element.