1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// map an object to an object
// Usage
// keep keys the same:
// @mgruel.objectMap({ a: 1 }, (key, value) => value + 1)
// change keys:
// @mgruel.objectMap({ a: 1 }, (key, value) => [key + "2", value + 1])
export const objectMap = async <
T extends object = object,
R extends any | [
string,
any,
] = any,
>(
obj: T,
fn: (key: string, value: T[keyof T]) => Promise<R>,
): Promise<Record<string, R>> =>
Object.fromEntries(
await Promise.all(
Object.entries(obj).map(async ([k, v]) => {
const res = await fn(k, v);
if (Array.isArray(res) && res.length === 2) {
return res;
}
else {
return [k, res];
}
}),
),
);
// forked from @stevekrouse.objectMap
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023