Skip to content

mapValues function ​

Transforms every value of an object, keeping its keys.

ts
import { mapValues } from 'utils';

Signature ​

ts
export function mapValues<T extends object, U>(
  object: T,
  mapper: (value: T[keyof T], key: keyof T & string) => U,
): Record<keyof T & string, U>

Parameters ​

NameDescription
TThe type of the object.
UThe type of the new values.
objectThe source object.
mapperReturns the new value of a property, from its value and its key.

Returns ​

A new object with the same keys.

Example ​

ts
mapValues({ rpm: 800.4, temperature: 72.25 }, (value) => formatDecimal(value, 1));
// { rpm: '800.4', temperature: '72.3' }

Tests ​

Line coverage: 100 %.

  • ✅ maps every value, keeping the keys
  • ✅ passes the key to the mapper
  • ✅ returns an empty object for an empty one

Source ​

src/object/map-values.ts (on GitHub)

Source code
ts
/**
 * Transforms every value of an object, keeping its keys.
 *
 * @template T - The type of the object.
 * @template U - The type of the new values.
 * @param object - The source object.
 * @param mapper - Returns the new value of a property, from its value and its key.
 * @returns A new object with the same keys.
 * @example
 * mapValues({ rpm: 800.4, temperature: 72.25 }, (value) => formatDecimal(value, 1));
 * // { rpm: '800.4', temperature: '72.3' }
 */
export function mapValues<T extends object, U>(
  object: T,
  mapper: (value: T[keyof T], key: keyof T & string) => U,
): Record<keyof T & string, U> {
  const result: Record<string, U> = {};
  for (const [key, value] of Object.entries(object)) {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- The own string keys of `T` and their values.
    result[key] = mapper(value as T[keyof T], key as keyof T & string);
  }
  return result;
}
Test file
ts
import { mapValues } from './map-values';

describe(mapValues, () => {
  it('maps every value, keeping the keys', () => {
    expect(mapValues({ rpm: 800, temperature: 72 }, (value) => value * 2)).toStrictEqual({
      rpm: 1600,
      temperature: 144,
    });
  });

  it('passes the key to the mapper', () => {
    expect(mapValues({ a: 1, b: 2 }, (value, key) => `${key}=${value}`)).toStrictEqual({ a: 'a=1', b: 'b=2' });
  });

  it('returns an empty object for an empty one', () => {
    expect(mapValues({}, () => 0)).toStrictEqual({});
  });
});

Keywords: map, values, objects, function

Generated from the JSDoc of the sources.