Home > Blockchain >  How to make object from array?
How to make object from array?

Time:01-28

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

CodePudding user response:

Use:

  • map to transform array items
  • Object.entries and Object.fromEntries
const groupBy = <T>(array: T[], predicate: (v: T) => string) =>
  array.reduce((acc, value) => {
    (acc[predicate(value)] ||= []).push(value);
    return acc;
  }, {} as { [key: string]: T[] });

const a = [
   { group: 'A', name: 'H', value: 10},
   { group: 'A', name: 'W', value: 20},
   { group: 'A', name: 'S', value: 30}
 ];

const transformSingleItemToEntry = (it: {name: string, value: number}) => [it.name,  it.value];

const groupped = groupBy(a, it => it.group);
const newObject = Object.fromEntries(
  Object.entries(groupped).map(
    e => [e[0],  Object.fromEntries(e[1].map(transformSingleItemToEntry)) ]
  )
);
console.log(newObject);

Playground link

CodePudding user response:

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.

  •  Tags:  
  • Related