CyrefJS
CCyrefJS
فا
Back to documentation
Object/Since 1.38.0

mapValues

Creates a new object by transforming the values of an object with an iteratee while preserving its keys.

mapValues(object, iteratee):{ [K in keyof T]: R }

How it works

For each own enumerable string-keyed property, the iteratee receives the property's value, key, and the original object. Its return value becomes the new value while the original key is preserved.

Iteratee arguments

The iteratee receives three arguments: the current value, the current key, and the original object.

Return type

The generic R represents the type returned by the iteratee. Every property in the resulting object therefore has the same R type.

Processed properties

The implementation uses Object.keys, so only own enumerable string-keyed properties are processed. Inherited, non-enumerable, and symbol-keyed properties are ignored.

Parameters

objectTrequired

The object whose values should be transformed.

iteratee(value: T[keyof T], key: keyof T, object: T) => Rrequired

A function that receives the current value, key, and original object and returns the new value.

Returns

{ [K in keyof T]: R }

A new object with the same keys as the original object and transformed values returned by the iteratee.

Examples

01

Basic usage

TypeScript
const prices = {
  apple: 10,
  banana: 20,
};

mapValues(prices, (value) => value * 2);
// {
//   apple: 20,
//   banana: 40,
// }
02

Transform values to strings

TypeScript
const scores = {
  math: 18,
  physics: 20,
};

mapValues(scores, (value) => `Score: ${value}`);
// {
//   math: "Score: 18",
//   physics: "Score: 20",
// }
03

Using the key

TypeScript
const prices = {
  apple: 10,
  banana: 20,
};

mapValues(prices, (value, key) => `${key}: ${value}`);
// {
//   apple: "apple: 10",
//   banana: "banana: 20",
// }
04

Using the original object

TypeScript
const data = {
  first: 10,
  second: 20,
};

mapValues(data, (value, key, object) => {
  return value + object.first;
});
// {
//   first: 20,
//   second: 30,
// }
05

Different return type

TypeScript
const users = {
  alice: 25,
  bob: 30,
};

mapValues(users, (value) => value >= 30);
// {
//   alice: false,
//   bob: true,
// }
06

Empty object

TypeScript
mapValues({}, () => "value");
// {}
07

Original object is unchanged

TypeScript
const data = {
  first: 10,
  second: 20,
};

const result = mapValues(data, (value) => value * 2);

console.log(data);
// {
//   first: 10,
//   second: 20,
// }
08

Inherited properties

TypeScript
const parent = {
  inherited: 10,
};

const data = Object.create(parent);
data.own = 20;

mapValues(data, (value) => value * 2);
// {
//   own: 40,
// }
Built with@cyref/js·Official documentation