Skip to content

Instantly share code, notes, and snippets.

@Graniron
Created September 8, 2022 15:41
Show Gist options
  • Save Graniron/2c5563a0165512b5e65af1e7a9efd693 to your computer and use it in GitHub Desktop.
Save Graniron/2c5563a0165512b5e65af1e7a9efd693 to your computer and use it in GitHub Desktop.
Reduce array of items into the Record with provided keys
/**
* 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