Typescript - A guide on updating the value of a key in a Map object

My Map is designed to store Lectures as keys and Arrays of Todos as values.

lecturesWithTodos: Map<Lecture, Todos[]> = new Map<Lecture, Todos[]>();

Initially, I set the key in the Map without any value since I will add the Todos later.

student.semester.lectures.forEach((lecture) => {
    this.lecturesWithTodos.set(lecture, []);
});

Now my goal is to assign each Todo to its corresponding Lecture key.

todos.forEach((todo) => {
   this.lecturesWithTodos.get(lecture).push(todo);
});

However, I keep encountering the error message "Cannot read property 'push' of undefined." While I could work around this issue by using a string as the key, I prefer using the Lecture object for simplicity. Is there a way to make the get method work with objects as keys?

Answer №1

To achieve your goal, a method is provided below that may be challenging when retrieving elements from the map in the future.


Consider the following types (adjust as needed):

interface Todos {
  id: number;
  name: string;
}

interface Lecture {
  id: number;
  name: string;
}

The data at hand:

 lectures: Lecture[] = [
    { id: 100, name: 'ENG' },
    { id: 200, name: 'PHY' },
    { id: 300, name: 'BIO' }
  ];

  todos: Todos[] = [
    { id: 100, name: 'Add' },
    { id: 100, name: 'Sub' },
    { id: 300, name: 'Mul' }
  ];

Methodology for creating the map

ngOnInit() {
   this.lectures.forEach(lecture => {
      this.lecturesWithTodos.set(lecture, []);
   });

   this.todos.forEach(todo => {
      const findLecture = this.findById(todo.id);
      const findAllTodos = this.findTodos(todo.id);

      if (findLecture && findAllTodos) {
        // Indicates a previous todo exists
        this.lecturesWithTodos.set(findLecture, [...findAllTodos, todo]);
      } else if (findLecture) {
        // Indicates a new todo being added
        this.lecturesWithTodos.set(findLecture, [todo]);
      }
  });

}

/** Function to locate Lecture by todo id **/
findById(id: number) {
    return Array.from(this.lecturesWithTodos.keys()).find(e => e.id === id);
}

/** Function to locate all previous todos by todo id **/
findTodos(id: number) {
    // todos is a 2D array
    let todos = Array.from(this.lecturesWithTodos.values());

    // Convert to 1D array for searching values
    return [].concat.apply([], todos).filter(e => e.id === id);
}

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

What is the importance of having a reference path for compiling an AngularJS 2 project using gulp-typescript?

I wanted to modify the Angular Tour Of Heros project to utilize gulp from this Github Repository. This is the gulpfile.json file I came up with: const gulp = require('gulp'); const del = require('del'); const typescript = require(&apo ...

What about combining a fat arrow function with a nested decorator?

Trying to implement a fat arrow function with a nestjs decorator in a controller. Can it be done in the following way : @Controller() export class AppController { @Get() findAll = (): string => 'This is coming from a fat arrow !'; } Wh ...

Encountering an error while utilizing ngForm in an HTML form

I have developed a custom component called "login", where I created an HTML form named "login.component.html". To convert this form into an Angular form, I added the code "" in login.component.html and imported import {NgForm} from '@angular/forms&apo ...

Unable to convert the value "Firefox" to the specified type 'Microsoft.VisualStudio.WebClient.Diagnostics.HtmlToolHost.PineZorro.DebugAdapterType'

I'm looking to switch from using Chrome to Firefox for my Angular project. I successfully installed the debug adapter from this link and it's working properly. However, when I attempted to replace launch.json in Vs2022, I encountered the followi ...

Steps for adding an input box to an md-menu item

I'm looking for an option that allows me to either add an item to an existing list or create a new one, similar to YouTube's 'Add to playlist' feature. The current implementation sort of works, but the menu disappears as soon as the inp ...

Get the socket identification from ngx-socket-io

After incorporating ngx-socket-io into my project, I encountered a hurdle while attempting to obtain the socket id. Is there anyone who has knowledge on how this can be accomplished? (I am utilizing service initialization instead of the one in the app Mo ...

Utilizing String.Format in TypeScript similar to C# syntax

Is there a way to achieve similar functionality to String.Format in C# using TypeScript? I'm thinking of creating a string like this: url = "path/{0}/{1}/data.xml" where I can substitute {0} and {1} based on the logic. While I can manually replace ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

Using Angular Material to create a data table with a fixed footer and paginator feature

I am facing a challenge with displaying the sum of rows data in the footer section of an Angular Material Table that has fixed footer and header, as well as a paginator. How can I calculate the sum of rows data to show in the footer? https://i.sstatic.net/ ...

How can I incorporate the LIKE operator in a query when dealing with PostgreSQL's String array type using TypeORM?

My database backend is PostgreSQL and I have a TypeORM object simplified as follows: @Entity() @Index(['name'], {unique: true}) export class Foo extends BaseEntity { @PrimaryGeneratedColumn('uuid') id: string; @Column() name: st ...

Avoiding the use of destructuring for undefined values in JavaScript can be achieved by implementing

Upon receiving the response registryReportSettings from the server: this.getRegistrySettings(registry.Id).subscribe((registryReportSettings: { extended: ReportPropertiesRequest }) => { const { objectProperties, reportProperties, textProperties } = reg ...

What advantages does Angular's Dependency Injection offer for a basic object setup?

The Angular documentation provides an example of injecting a value (configuration object) using @inject in the constructor for scenarios where a class is not being injected. https://angular.io/guide/dependency-injection#non-class-dependencies I managed t ...

Do I have to wait for the HTTP get request to access the fetched object property?

I am currently working with Angular and TypeScript on a dish-detail component that is accessed through 'dishes/:id' The dish object returned has a property called components, which contains an array of objects with two properties: id: type stri ...

Is it possible to generate an array of objects, where each object includes an observable retrieved through forkJoin?

let food = { id: 1, isTasty: false } Imagine I have a custom function that takes the ID of a food item and returns an observable which resolves to a boolean indicating whether the food is tasty or not. I wish to loop through an array of food items an ...

Inheritance-based generic type inference in Typescript

Take a look at this piece of code: class A<T> { t?: T; } interface B {} class C implements A<B> {} function f<T1 extends A<T2>, T2>(a: T1): T2 | undefined { return a.t; } const result = f(new C()); const result2 = f(new A<B> ...

Problem with Jasmine in Angular 5 within Visual Studio Code

I am completely new to Angular 5 Unit testing and facing some challenges. Despite installing all @types/jasmine, I am encountering errors in my spec.ts file such as 'describle is not a name' and 'jasmine.createSpyObj does not exist on the ty ...

What is the process of creating the /dist folder in an unreleased version of an npm package?

Currently working on implementing a pull request for this module: https://github.com/echoulen/react-pull-to-refresh ... It seems that the published module generates the /dist folder in the package.json prepublish npm script. I have my local version of the ...

What is the way to send custom properties to TypeScript in combination with StyledComponents?

Encountering an error while attempting to implement Styled Components 3 with TypeScript: TS2365: Operator '<' cannot be applied to types 'ThemedStyledFunction<{}, any, DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, ...

What is the best way to format this DateTime for a more visually appealing appearance within an Angular Material <mat-card-subtitle>?

My date looks like this: 2000-12-16T00:00:00 When displayed in Material code (as the publish_date): <mat-card *ngFor="let book of bookItems"> <mat-card-header > <mat-card-title>{{book.title | titlecase}}</mat-card-title> ...

Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing. In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data an ...