1.38.0mapValues
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
objectTrequiredThe object whose values should be transformed.
iteratee(value: T[keyof T], key: keyof T, object: T) => RrequiredA 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
Basic usage
const prices = {
apple: 10,
banana: 20,
};
mapValues(prices, (value) => value * 2);
// {
// apple: 20,
// banana: 40,
// }Transform values to strings
const scores = {
math: 18,
physics: 20,
};
mapValues(scores, (value) => `Score: ${value}`);
// {
// math: "Score: 18",
// physics: "Score: 20",
// }Using the key
const prices = {
apple: 10,
banana: 20,
};
mapValues(prices, (value, key) => `${key}: ${value}`);
// {
// apple: "apple: 10",
// banana: "banana: 20",
// }Using the original object
const data = {
first: 10,
second: 20,
};
mapValues(data, (value, key, object) => {
return value + object.first;
});
// {
// first: 20,
// second: 30,
// }Different return type
const users = {
alice: 25,
bob: 30,
};
mapValues(users, (value) => value >= 30);
// {
// alice: false,
// bob: true,
// }Empty object
mapValues({}, () => "value");
// {}Original object is unchanged
const data = {
first: 10,
second: 20,
};
const result = mapValues(data, (value) => value * 2);
console.log(data);
// {
// first: 10,
// second: 20,
// }Inherited properties
const parent = {
inherited: 10,
};
const data = Object.create(parent);
data.own = 20;
mapValues(data, (value) => value * 2);
// {
// own: 40,
// }