Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

mapValues

Maps an object's values using a transform function.

TypeScript
Copied!
1/**
2 * Maps an object's values using a transform function.
3 *
4 * @param obj - The source object.
5 * @param fn - A function that transforms each value.
6 * @returns A new object with the same keys and transformed values.
7 */
8export function mapValues<T, U>(
9  obj: Record<string, T>,
10  fn: (val: T, key: string) => U
11): Record<string, U> {
12  return Object.keys(obj).reduce((acc, key) => {
13    acc[key] = fn(obj[key], key);
14    return acc;
15  }, {} as Record<string, U>);
16}
  • Value-Centric Transformation

    Applies a transformation function to all values while preserving keys, offering fine-grained control over object content.

  • Key-Aware Mapping

    Passes both value and key to the callback, enabling context-sensitive transformations.

  • Type-Safe and Generic

    Utilizes TypeScript generics to ensure the output types are correctly inferred and validated.

  • Immutable Output

    Returns a new object without mutating the original, promoting safer and more predictable data flow.

Tests | Examples

TypeScript
Copied!
1test('mapValues - transforms values using provided function', () => {
2  const input = { a: 1, b: 2, c: 3 };
3  const output = mapValues(input, val => val * 2);
4  expect(output).toEqual({ a: 2, b: 4, c: 6 });
5});
6
7test('mapValues - includes keys in the callback', () => {
8  const input = { x: 10, y: 20 };
9  const output = mapValues(input, (val, key) => `${key}:${val}`);
10  expect(output).toEqual({ x: 'x:10', y: 'y:20' });
11});
12
13test('mapValues - works with empty object', () => {
14  const result = mapValues({}, val => val);
15  expect(result).toEqual({});
16});
17
18test('mapValues - does not mutate original object', () => {
19  const input = { foo: 1 };
20  const original = { ...input };
21  mapValues(input, val => val + 1);
22  expect(input).toEqual(original);
23});

Common Use Cases

  • Data Normalization

    Convert raw values (e.g., strings to numbers, booleans to flags) across an entire object.

  • UI Formatting

    Transform internal values into display-friendly formats (e.g., currency, dates, labels).

  • Configuration or Settings Mapping

    Apply defaults, constraints, or transformations to config objects before usage.

  • API Response Transformation

    Process backend data before rendering or further manipulation.

  • Batch Computations

    Apply calculations or condition-based changes to sets of keyed values (e.g., metrics, scores, prices).

Codebase: Utilities -> Objects -> mapValues | Yevhen Klymentiev