To convert an array of objects and extract their keys into variables, the method that can be used is by utilizing an Array reducer.
If we want to specify our types, a TypeScript Record
can be quite handy, especially for dealing with objects that have dynamic keys.
The process involves iterating through the entries of the array, which essentially transforms objects into an array of key-value pairs. Then, further iterating through the values within those objects enables us to extract them into separate variables representing name and value. The group information can be derived from the outer tuples' keys.
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 approach allows us to flatten an array containing nested objects into a single-dimensional array of objects.