its a common question in javascript to covert an array of objects to an object of arrays, but how do you do it in Typescript with full typing support?
2 Answers
type Pivot<T> = {
[K in keyof T]: T[K][];
}
function pivot<T extends Record<any, any>>(items: T[]): Pivot<T> {
return Object.keys(items[0]).reduce((obj, key) => {
obj[key] = items.map(item => item[key])
return obj
}, {} as Pivot<T>)
}
If this doesn't work at run-time please provide example inputs and outputs. If this is not sufficient "typing support" please add examples that should be rejected and accepted at compile-time.
1 Comment
swyx
this is really great. i like how concise it is. i'll definitely provide examples in a future question, for now i'm still learning :) thank you and accepted the answer
do it like this
**
* convert an array of (non nested) objects to an object of arrays.
* assumes all objects are the same shape
* */
type IndexObject = { [index: string]: any }; // hacky. :(
function pivot<T>(arr: (T & IndexObject)[]) {
type Subset = { [K in keyof T]?: T[K] }; // make it optional to build the return array
let ans: IndexObject & Subset = {};
Object.keys(arr[0]).forEach(k => {
ans[k] = arr.map(obj => obj[k]);
});
return ans as { [K in keyof T]: T[K] }; // take out the optionality of every key
}
happy to see better ideas if you have em