What are the steps to create an object from an array?

Is it possible to create an object from an array in TypeScript?

{ A: {H: 10, 
         W: 20,
         S: 30}}

using the following data:

[
    { group: A, name: H, value: 10 }, 
    { group: A, name: W, value: 20},
    { group: A, name: S, value: 30}
]

Let's explore how this can be achieved in a TypeScript environment.

Answer №1

Here are some useful techniques:

  • map function can be used to transform array items
  • Utilize both 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);

Check out the playground for experimentation

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Proper method for displaying modifications in QueryList from @ContentChildren

I'm having trouble with rendering components and here is the code snippet: <my-component> <ng-template *ngFor="let item of data"> <child-component> <div> {{ data.title }} </div> </child-c ...

Error: Unable to attach the "identity" property as the object does not support extension

I encountered a simple TypeError while attempting to format my POST body. Below is the function I am using for handleSubmit : const handleSubmit = (values: any, formikHelpers: FormikHelpers<any>) => { const prepareBody = { ...values.customerC ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Is it possible to globally modify the component reference <dropdown-component> name in Angular during runtime in a dynamic manner?

I am currently working on an application that utilizes a component called "dropdown-component" throughout its pages. However, due to specific business requirements, I have been tasked with replacing "dropdown-component" with "custom-dropdown-component". Un ...

Using React Material UI to create multiple collapse components

Currently, I am facing an issue where all the collapses in my list are linked to one state for "open." This means that if I open one list, all the other lists also open. I am looking for a way to keep the collapses separate from each other without needing ...

Invalid information found within session array

My array is containing incorrect numbers <script> var id=0; function getId(id2){ id=id2; document.getElementById("idHid").value=id; document.getElementById("form").submit(); } </script> <?php $n = 10; $st = 0; $_SESSION['cel']= ...

Using the captured group as an array index in preg_replace with PHP

It appears that this task should be simple, but for some reason the code provided is not functioning correctly: $text = preg_replace('/test([0-9]+)/i', $array["$1"], $text); The intention of this code is to identify all occurrences such as &apo ...

Encountering error 2307 "Cannot find module" when using Vue 3 with script setup and TypeScript

I am currently attempting to run unit tests in my Vue3 project using vue/test-utils and jest. Upon running the npm run test script, the test fails due to an error with the import: error TS2307: Cannot find module 'pathtofile/file.vue' I have tr ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

AngularJS: Using $watch to retrieve the index of the modified item within an array

My current situation involves an array containing multiple objects. $scope.userCompetences = []; To monitor any changes in this array, I have implemented a deep watch: $scope.$watch('userCompetences', function (newVal, oldValue) { ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Struggle with Loading Custom Templates in Text Editor (TinyMCE) using Angular Resolver

My goal is to incorporate dynamic templates into my tinyMCE setup before it loads, allowing users to save and use their own templates within the editor. I have attempted to achieve this by using a resolver, but encountered issues with the editor not loadin ...

Tips for successfully interacting with dynamic text areas using Protractor:

My current project involves e2e testing for an Angular 4 application with Protractor. Despite my efforts, I am struggling to locate a unique id, class, name or text identifier for a specific textarea within the application code. I need assistance in find ...

Angular Pipe: Working with Data Structures in Angular With Nested Arrays and Objects

After struggling to customize answers for similar questions, I find myself in need of some assistance. My current challenge involves using an angular pipe to filter the following data structure: subjects = [ { name: "subject1", keywords:[& ...

Analyzing nested arrays against dictionary keys

Here is the array I am working with: [[ 36 119] [ 36 148] [ 36 179] [ 67 209] [ 69 84] [ 96 240]] In addition, I have a dictionary that looks like this: {84: [36, 119], 85: [36, 148], 86: [36, 160]} My goal is to identify if any values from the arra ...

Issues with PHP server handling JSON files

I'm having some trouble retrieving server data to display in a table on my iPhone. The process involves the standard flow of server - php_interface - iOS. Initially, I attempted to use an echo json_encode(array) setup, but ran into issues with populat ...

Crafting interactive buttons with angular material

I've been working on an angular application where I created 5 mat flat buttons using angular material. <button mat-flat-button [ngClass]="this.selected == 1 ? 'tab_selected' : 'tab_unselected'" (click)="change(1)">B-L1</b ...

Can you identify the type of component that is returned from the withStyles() function?

My project includes a simple Dictionary component with basic properties: interface DictionaryProps { word: string; } In another component's props, I am looking for a generic component that only requires a string word: dictionary: React.ComponentC ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...