I have array of object data and I want to dynamically convert them to object with key and array. How to make make keys of objects to work dynamically in typescript?
For example if the data be like:
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' },
]
and I it to convert 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']
}
The simplest solution is to
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 increase, is there any better and more concise solution?
Something like this will work in javascript but not 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 it will return an error of typing.