|
| 1 | +# mapValuesAsync |
| 2 | + |
| 3 | +Returns a new object with values transformed through an async function. |
| 4 | + |
| 5 | +```typescript |
| 6 | +const newObj = await mapValuesAsync(object, getNewValue); |
| 7 | +``` |
| 8 | + |
| 9 | +## Usage |
| 10 | + |
| 11 | +### `mapValuesAsync(object, getNewValue, options?)` |
| 12 | + |
| 13 | +Use `mapValuesAsync` when you want to create a new object by asynchronously transforming each value. Keys remain the same, and only the values are changed to the resolved results of the `getNewValue` function. |
| 14 | + |
| 15 | +```typescript |
| 16 | +import { mapValuesAsync } from 'es-toolkit/object'; |
| 17 | + |
| 18 | +// Double all values |
| 19 | +const numbers = { a: 1, b: 2, c: 3 }; |
| 20 | +const doubled = await mapValuesAsync(numbers, async value => value * 2); |
| 21 | +// doubled becomes { a: 2, b: 4, c: 6 } |
| 22 | + |
| 23 | +// Convert string values to uppercase |
| 24 | +const strings = { first: 'hello', second: 'world' }; |
| 25 | +const uppercased = await mapValuesAsync(strings, async value => value.toUpperCase()); |
| 26 | +// uppercased becomes { first: 'HELLO', second: 'WORLD' } |
| 27 | + |
| 28 | +// Use both key and value |
| 29 | +const scores = { alice: 85, bob: 90, charlie: 95 }; |
| 30 | +const grades = await mapValuesAsync(scores, async (value, key) => `${key}: ${value >= 90 ? 'A' : 'B'}`); |
| 31 | +// grades becomes { alice: 'alice: B', bob: 'bob: A', charlie: 'charlie: A' } |
| 32 | + |
| 33 | +// Limit concurrency. |
| 34 | +const items = { a: 1, b: 2, c: 3 }; |
| 35 | +await mapValuesAsync(items, async item => await processItem(item), { concurrency: 2 }); |
| 36 | +// Only 2 values are processed concurrently at most. |
| 37 | +``` |
| 38 | + |
| 39 | +#### Parameters |
| 40 | + |
| 41 | +- `object` (`T extends object`): The object to transform values from. |
| 42 | +- `getNewValue` (`(value: T[K], key: K, object: T) => Promise<V>`): An async function that generates new values. Receives value, key, and the entire object as parameters. |
| 43 | +- `options` (`MapValuesAsyncOptions`, optional): Options to control concurrency. |
| 44 | + - `concurrency` (`number`, optional): Maximum number of concurrent operations. If not specified, all operations run concurrently. |
| 45 | + |
| 46 | +#### Returns |
| 47 | + |
| 48 | +(`Promise<Record<K, V>>`): A promise that resolves to a new object with transformed values. |
0 commit comments