2

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 2

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.