mapKeys
mapKeys
(mapperFn: MapperFn) => (collection: KeyedCollection) => KeyedCollection
Change each key of a collection
Below we have some accounts keyed by id. Let's instead key them by email
const accountsById = { j0N7: { id: 'j0N7', email: 'tom@example.com' }, b5sS: { id: 'b5sS', email: 'ken@example.com' }, yjdk: { id: 'yjdk', email: 'chris@example.com' }, } const mapToEmailKeys = mapKeys(get('email')) const accountsByEmail = mapToEmailKeys(accountsById) console.log(accountsByEmail) // is { // tom@example.com: { // id: j0N7 // email: tom@example.com // } // ken@example.com: { // id: b5sS // email: ken@example.com // } // chris@example.com: { // id: yjdk // email: chris@example.com // } // }
type Account = { id: string email: string } type Directory = Record<string, Account> const accountsById: Directory = { j0N7: { id: 'j0N7', email: 'tom@example.com' }, b5sS: { id: 'b5sS', email: 'ken@example.com' }, yjdk: { id: 'yjdk', email: 'chris@example.com' }, } const getEmail = get('email')<Account> const mapToEmailKeys = mapKeys(getEmail)<Directory> const accountsByEmail = mapToEmailKeys(accountsById) console.log(accountsByEmail) // is { // tom@example.com: { // id: j0N7 // email: tom@example.com // } // ken@example.com: { // id: b5sS // email: ken@example.com // } // chris@example.com: { // id: yjdk // email: chris@example.com // } // }
const accountsById = { j0N7: { id: 'j0N7', email: 'tom@example.com' }, b5sS: { id: 'b5sS', email: 'ken@example.com' }, yjdk: { id: 'yjdk', email: 'chris@example.com', }, } const mapToEmailKeys = mapKeys(get('email')) const accountsByEmail = mapToEmailKeys(accountsById) console.log(accountsByEmail) // is { // tom@example.com: { // id: j0N7 // email: tom@example.com // } // ken@example.com: { // id: b5sS // email: ken@example.com // } // chris@example.com: { // id: yjdk // email: chris@example.com // } // }
type Account = { id: string email: string } type Directory = Record<string, Account> const accountsById: Directory = { j0N7: { id: 'j0N7', email: 'tom@example.com' }, b5sS: { id: 'b5sS', email: 'ken@example.com' }, yjdk: { id: 'yjdk', email: 'chris@example.com', }, } const getEmail = get('email')<Account> const mapToEmailKeys = mapKeys( getEmail )<Directory> const accountsByEmail = mapToEmailKeys(accountsById) console.log(accountsByEmail) // is { // tom@example.com: { // id: j0N7 // email: tom@example.com // } // ken@example.com: { // id: b5sS // email: ken@example.com // } // chris@example.com: { // id: yjdk // email: chris@example.com // } // }
See 'What' for example code.
One use case is when we have a collection with multiple unique properties. Different parts of the application may have access to one of these properties, but not all. In these situations, it's helpful to map the collection by the available key.