Skip to content

Instantly share code, notes, and snippets.

@xiongchengqing
Forked from steveruizok/mapValues.ts
Last active September 17, 2021 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiongchengqing/409e41ec048386cd07e5fc1d4a530cd5 to your computer and use it in GitHub Desktop.
Save xiongchengqing/409e41ec048386cd07e5fc1d4a530cd5 to your computer and use it in GitHub Desktop.
Map values.
/**
* 外提
*
* @param obj
* @param fn
* @returns remapped obj
*/
export function remap<P, T>(
obj: { [key: string]: T },
fn: (value: T, index: number) => P
): { [key: string]: P } {
return Object.fromEntries(
Object.entries(obj).map(([id, value], index) => [id, fn(value, index)])
)
}
// EXAMPLE
const users = {
fred: { age: 31, addr: 'steven str. road 31st' },
tom: { age: 24, addr: 'heaven str. road 12nd' }
}
// {"fred":31,"tom":24}
const result = remap(users, user => user.age)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment