Skip to content

Instantly share code, notes, and snippets.

@noahm
Last active March 24, 2022 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noahm/268849b942de8ae6fcbc7845497de961 to your computer and use it in GitHub Desktop.
Save noahm/268849b942de8ae6fcbc7845497de961 to your computer and use it in GitHub Desktop.
type ArraysOfEachProperty<T> = {
[Property in keyof T]: Array<T[Property]>;
}
function fieldArrsToObjs<T extends {}>(arrs: ArraysOfEachProperty<T>): Array<T> {
const ret: T[] = [];
Object.entries(arrs).forEach(([key, values]) => {
(values as unknown[]).forEach((value, idx) => {
if (!ret[idx]) {
// @ts-expect-error
ret[idx] = { [key]: value };
} else {
// @ts-expect-error
ret[idx][key] = value;
}
});
});
return ret;
}
/**
* Inferred type of legCounts:
* Array<{ animal: string, legs: number }>
*/
const legCounts = fieldArrsToObjs({
animal: ["dog", "cat", "bird"],
legs: [4, 4, 2],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment