CyrefJS
CCyrefJS
فا
Back to documentation
Object/Since 1.38.0

mapKeys

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

objectTrequired

The object whose keys should be transformed.

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

A 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

01

Basic usage

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

mapKeys(users, (value, key) => key.toUpperCase());
// {
//   ALICE: 25,
//   BOB: 30,
// }
02

Create keys from values

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

mapKeys(users, (value) => `age-${value}`);
// {
//   "age-25": 25,
//   "age-30": 30,
// }
03

Using the key and value

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

mapKeys(users, (value, key) => `${key}-${value}`);
// {
//   "alice-25": 25,
//   "bob-30": 30,
// }
04

Using the original object

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

mapKeys(data, (value, key, object) => {
  return key === "first"
    ? "primary"
    : String(value + object.first);
});
// {
//   primary: 10,
//   "30": 20,
// }
05

Numeric keys

TypeScript
const data = {
  first: "A",
  second: "B",
};

mapKeys(data, (value, key) => key === "first" ? 1 : 2);
// {
//   "1": "A",
//   "2": "B",
// }
06

Symbol keys

TypeScript
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.
07

Duplicate new keys

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

mapKeys(data, () => "value");
// {
//   value: 20,
// }
08

Empty object

TypeScript
mapKeys({}, () => "key");
// {}
09

Original object is unchanged

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

const result = mapKeys(data, (value, key) => key.toUpperCase());

console.log(data);
// {
//   first: 10,
//   second: 20,
// }
Built with@cyref/js·Official documentation