Code Snippets
/

Map Over an Object's Values

Map Over an Object's Values

JavaScript objects have no built-in `mapValues` like Ramda or Underscore, so every codebase eventually grows its own. This snippet covers the canonical `Object.fromEntries` transform, a sibling `mapKeys` for renaming, and a combined version that lets you reshape both keys and values in one pass. Use them to coerce types, format display strings, or normalise API payloads in a few lines.

JavaScript
Easy
3 snippets
utility
code-template
functional-programming

815 views

11

function mapValues(obj, fn) {
    return Object.fromEntries(
        Object.entries(obj).map(([k, v]) => [k, fn(v, k)])
    );
}

const prices = { apple: 1, banana: 2, cherry: 3 };
console.log(mapValues(prices, (n) => n * 100));
// { apple: 100, banana: 200, cherry: 300 }

const raw = { id: '1', count: '42' };
console.log(mapValues(raw, Number));
// { id: 1, count: 42 }

The two-step entries then fromEntries pipeline is the most readable functor-like transform in plain JavaScript. Passing both value and key to the callback (in that order, matching Array#map) lets the caller branch on the key when needed without forcing a separate helper. This runs in O(n) time and allocates two intermediate arrays plus the result; for hot paths with thousands of keys, prefer the manual loop variant in the next accordion. Use this version for one-shot transforms where readability beats raw throughput.