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β
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]