keyBy (for Maps) ​
Maps each entry of a Map based on a provided key-generating function.
typescript
const result = keyBy(map, getKeyFromEntry);INFO
This function is available exclusively from es-toolkit/map to avoid potential conflicts with similar functions for other collection types.
Usage ​
keyBy(map, getKeyFromEntry) ​
Use keyBy when you want to reorganize a Map by generating new keys from the values. Provide a function that generates a key from each value-key pair, and it returns a new Map where the keys are generated by the key function and the values are the corresponding values from the original map. If multiple entries produce the same key, the last value encountered will be used.
typescript
import { keyBy } from 'es-toolkit/map';
const map = new Map([
['x', { type: 'fruit', name: 'apple' }],
['y', { type: 'fruit', name: 'banana' }],
['z', { type: 'vegetable', name: 'carrot' }],
]);
const result = keyBy(map, item => item.type);
// Result:
// Map(2) {
// 'fruit' => { type: 'fruit', name: 'banana' },
// 'vegetable' => { type: 'vegetable', name: 'carrot' }
// }
// Note: 'banana' is kept because it was the last 'fruit' encounteredYou can reorganize data based on various criteria.
typescript
import { keyBy } from 'es-toolkit/map';
// Index by ID property
const users = new Map([
['user1', { id: 101, name: 'Alice', role: 'admin' }],
['user2', { id: 102, name: 'Bob', role: 'user' }],
['user3', { id: 103, name: 'Charlie', role: 'user' }],
]);
const byId = keyBy(users, user => user.id);
// Result: Map with keys 101, 102, 103
// Index by role (last user per role wins)
const byRole = keyBy(users, user => user.role);
// Result: Map(2) {
// 'admin' => { id: 101, name: 'Alice', role: 'admin' },
// 'user' => { id: 103, name: 'Charlie', role: 'user' }
// }
// Transform keys using both value and original key
const inventory = new Map([
['item_1', { category: 'electronics', price: 100 }],
['item_2', { category: 'electronics', price: 200 }],
]);
const categorized = keyBy(inventory, (value, key) => `${value.category}_${key}`);
// Result: Map with keys 'electronics_item_1', 'electronics_item_2'Parameters ​
map(Map<K, V>): The map of entries to be mapped.getKeyFromEntry((value: V, key: K, object: Map<K, V>) => K2): A function that generates a key from a value-key pair.
Returns ​
(Map<K2, V>): A Map where the generated keys are mapped to each entry's value.

