castMapping()
castMapping<
Item,Key>(key): (item) =>Item[Key]
castMapping<
Item,Result>(mapper): (item) =>Result
castMapping<
Item>(input?): (item) =>Item
Creates a mapping function from a property key, function, or identity.
Type Parametersโ
Item: Itemโ
The type of items being mapped.
Key: Key extends string | number | symbolโ
The type of the property key.
Result: Resultโ
The type of the mapping result.
Parametersโ
Overload 1:
key: Keyโ
Overload 2:
mapper: (item) => Resultโ
Overload 3:
input?: nullโ
Property key, mapping function, or nullish (identity).
Returns: (item): Item[Key]โ
A mapping function.
item:
Item
Returns:Item[Key]
Sinceโ
2.0.0
Also known asโ
castMapping (Radashi) ยท iteratee (Lodash) ยท โ (es-toolkit, Remeda, Ramda, Effect, Modern Dash, Antfu)
Exampleโ
const users = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }];
// Property key โ accessor
users.map(castMapping('name'));
// => ['Alice', 'Bob']
// Function โ itself
users.map(castMapping((u) => u.name.length));
// => [5, 3]
// Nullish โ identity
users.map(castMapping());
// => [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]
How it works?โ
Creates a mapping function from a property key, function, or nullish value.
Usage Exampleโ
Input Typesโ
| Input | Output Function |
|---|---|
'name' | (item) => item.name |
(x) => x.id | (x) => x.id |
null / undefined | (item) => item |
Use Casesโ
Property access simplification ๐โ
Convert string property names to property accessor functions automatically. Essential for reducing boilerplate in data transformation.
const users = [{ id: 1 }, { id: 2 }];
const ids = users.map(castMapping("id"));
// [1, 2]
Flexible API designโ
Create functions that accept either property names or mapping functions. Essential for building intuitive, flexible APIs.
function extract(items, mapper) {
const fn = castMapping(mapper);
return items.map(fn);
}
extract(users, "id"); // [1, 2]
extract(users, (u) => u.id * 2); // [2, 4]