Created
September 8, 2022 15:41
-
-
Save Graniron/2c5563a0165512b5e65af1e7a9efd693 to your computer and use it in GitHub Desktop.
Reduce array of items into the Record with provided keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Reduce array of items into the Record with provided keys | |
* reduceToRecord('id', 'name', items): [{ id: 'id1', name: 'John', type: 'web' }] => { id1: 'John' } | |
*/ | |
export const reduceToRecord = <T, U>(keyName: string, valueName: string, items: U[]): Record<string, T> => { | |
const keyWithNameReducer = (acc: Record<string, T>, item: U) => { | |
const key = item[keyName]; | |
const value = item[valueName]; | |
return { | |
...acc, | |
...(key && { [key]: value }), | |
}; | |
}; | |
return items.reduce(keyWithNameReducer, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment