Is there a way in TypeScript to convert an array of objects into an object with keys and arrays dynamically?
For instance, given the following data:
data1 = [
{a: 'st1', b: 1, c: 1, d: 1, e: 'e1' },
{a: 'st2', b: 2, c: 2, d: 2, e: 'e2'},
{a: 'st3', b: 3, c: 3, d: 3, e: 'e3'},
{a: 'st4', b: 4, c: 4, d: 4, e: 'e4' },
]
We want to convert it to:
data2= {
a: ['st1', 'st2', 'st3', 'st4'],
b: [1, 2, 3, 4],
c: [1, 2, 3, 4],
d: [1, 2, 3, 4],
e: ['e1', 'e2', 'e3', 'e4']
}
While a simple solution using type definitions is:
type Data2Props = {
a: string[],
b: number[],
c: number[],
d: number[],
e: string[]
}
const data2: Data2Props = {
a: [],
b: [],
c: [],
d: [],
e: []
}
data1?.forEach((item) => {
data2.a.push(item.a)
data2.b.push(item.b)
data2.c.push(item.c)
data2.d.push(item.d)
data2.e.push(item.e)
})
But what if the number of keys increases? Is there a more concise solution?
While the following JavaScript code works, it throws errors in TypeScript:
let keys: string[] = ['a', 'b', 'c', 'd', 'e'];
let data2 = {}
keys.forEach((key) => data2[key] = [])
data1?.forEach((item) => {
keys.forEach((key) => data2[key].push(item[key])
}
In TypeScript, this would result in a typing error.