flattenListOfObjects.tsx 830 B

1234567891011121314151617181920212223242526
  1. /**
  2. * Given a list of objects (or maps) of `string` -> `any[]`,
  3. * merge the arrays of each key in the object.
  4. *
  5. * e.g. [{a: [1]}, {a: [2]}, {b: [3]}] ==> {a: [1, 2], b: {3}}
  6. *
  7. * Any non-array values will throw an exception
  8. */
  9. export default function flattenListOfObjects(
  10. objs: Array<Record<string, any[] | undefined>>
  11. ) {
  12. return objs.reduce((acc, obj) => {
  13. Object.entries(obj).forEach(([key, value]) => {
  14. if (!Array.isArray(value)) {
  15. // e.g. if value is undefined (otherwise, a non-Array type will get caught by ts)
  16. // TS doesn't like our test where object keys are no equivalent, so we
  17. // need to allow `undefined` as a valid type in the Record.
  18. throw new Error('Invalid value');
  19. }
  20. acc[key] = (acc[key] || []).concat(value);
  21. });
  22. return acc;
  23. }, {});
  24. }