'How to make object from array?
how to make an object from an array
{ A: {H: 10,
W: 20,
S: 30}}
from
[
{ group: A, name: H, value: 10 },
{ group: A, name: W, value: 20},
{ group: A, name: S, value: 30}
]
in a typescript
Solution 1:[1]
In order to transform an array of objects, and extract their keys to variables, we can use an Array reducer.
To define our types, a TypeScript Record should do the trick, this works well for objects with variable keys.
We're looping through the entries of the array, which turns objects into an array of key-value tuples, then looping through the entries of the values of that object in order to extract them to the name, and value. The group can be inferred from the key of the outside tuples.
type InnerRecord = Record<string, number>;
type OuterRecord = Record<string, InnerRecord>;
interface TransformedRecord {
group: string;
name: string;
value: number;
};
const record: OuterRecord = {
A: { H: 10, W: 20, S: 30 },
B: { H: 15, W: 25, S: 35 },
C: { H: 20, W: 30, S: 40 },
};
const transformRecord = (toTransform: OuterRecord) => {
return Object.entries(toTransform).reduce(
(accumulator, [group, values]) => [
...accumulator,
...Object.entries(values).map(([name, value]) => ({ group, name, value, })),
],
[]
);
};
const transformed: TransformedRecord[] = transformRecord(record);
console.log(transformed);
/** OUTPUT:
* [ { group: 'A', name: 'H', value: 10 },
{ group: 'A', name: 'W', value: 20 },
{ group: 'A', name: 'S', value: 30 },
{ group: 'B', name: 'H', value: 15 },
{ group: 'B', name: 'W', value: 25 },
{ group: 'B', name: 'S', value: 35 },
{ group: 'C', name: 'H', value: 20 },
{ group: 'C', name: 'W', value: 30 },
{ group: 'C', name: 'S', value: 40 } ]
*/
This will take us from an array of nested objects, to a one-dimensional array of objects.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
