1.38.0mapKeys
Creates a new object by transforming the keys of an object with an iteratee while preserving the original values.
mapKeys(object, iteratee):Record<K, T[keyof T]>How it works
For each own enumerable string-keyed property, the iteratee receives the property's value, key, and the original object. The returned value becomes the new key while the original value is preserved.
Iteratee arguments
The iteratee receives three arguments: the current value, the current key, and the original object.
Duplicate keys
If multiple properties produce the same new key, the later property overwrites the earlier value.
Processed properties
The implementation uses Object.keys, so inherited properties, non-enumerable properties, and symbol-keyed properties from the original object are ignored.
Parameters
objectTrequiredThe object whose keys should be transformed.
iteratee(value: T[keyof T], key: keyof T, object: T) => KrequiredA function that receives the current value, key, and original object and returns the new key.
Returns
Record<K, T[keyof T]>A new object containing the original values under the keys returned by the iteratee.
Examples
Basic usage
const users = {
alice: 25,
bob: 30,
};
mapKeys(users, (value, key) => key.toUpperCase());
// {
// ALICE: 25,
// BOB: 30,
// }Create keys from values
const users = {
alice: 25,
bob: 30,
};
mapKeys(users, (value) => `age-${value}`);
// {
// "age-25": 25,
// "age-30": 30,
// }Using the key and value
const users = {
alice: 25,
bob: 30,
};
mapKeys(users, (value, key) => `${key}-${value}`);
// {
// "alice-25": 25,
// "bob-30": 30,
// }Using the original object
const data = {
first: 10,
second: 20,
};
mapKeys(data, (value, key, object) => {
return key === "first"
? "primary"
: String(value + object.first);
});
// {
// primary: 10,
// "30": 20,
// }Numeric keys
const data = {
first: "A",
second: "B",
};
mapKeys(data, (value, key) => key === "first" ? 1 : 2);
// {
// "1": "A",
// "2": "B",
// }Symbol keys
const first = Symbol("first");
const second = Symbol("second");
const data = {
first: "A",
second: "B",
};
mapKeys(data, (value, key) => {
return key === "first" ? first : second;
});
// The resulting object uses the returned symbols as keys.Duplicate new keys
const data = {
first: 10,
second: 20,
};
mapKeys(data, () => "value");
// {
// value: 20,
// }Empty object
mapKeys({}, () => "key");
// {}Original object is unchanged
const data = {
first: 10,
second: 20,
};
const result = mapKeys(data, (value, key) => key.toUpperCase());
console.log(data);
// {
// first: 10,
// second: 20,
// }