normalize.ts 455 B

12345678910111213141516171819202122
  1. import mapKeys from 'lodash/mapKeys'
  2. export interface NormalizedObject<T> {
  3. [p: string]: T
  4. }
  5. type Data<T> = T[]
  6. type Config = Partial<{
  7. idAttribute: string
  8. }>
  9. export function normalize<T>(
  10. data: Data<T>,
  11. config: Config = {}
  12. ): NormalizedObject<T> | undefined {
  13. const { idAttribute = 'id' } = config
  14. const mapped = mapKeys(data, idAttribute)
  15. return Object.prototype.hasOwnProperty.call(mapped, 'undefined')
  16. ? undefined
  17. : mapped
  18. }