JavaScript

Transform object values with entries and fromEntries

Convert an object into entries, transform the key-value pairs, then rebuild it with Object.fromEntries. This is useful for explicit transformations of a flat configuration object.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const prices = {small: 5, large: 9};
const cents = Object.fromEntries(
  Object.entries(prices).map(([key, value]) => [key, value * 100])
);
console.log(JSON.stringify(cents));

How it works

Object.entries supplies enumerable own string-keyed properties as pairs. Each mapped pair keeps its key and replaces its numeric value. FromEntries consumes the pairs and creates a new ordinary object. The original prices object is not modified.

Limits and mistakes

This recipe does not include symbol-keyed properties and is not a recursive object transformation. Repeated output keys overwrite earlier entries. Validate arbitrary input keys before assigning them into other objects or configuration systems.

Check the result

Expect {"small":500,"large":900}. Check that prices still contains 5 and 9. If you rename keys, test for collisions that might silently replace a result.

Sources

Reference documentation for the behavior used in this guide: