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

Steps for sending a POST request for every file in the given array

I am working on an angular component that contains an array of drag'n'dropped files. My goal is to make a POST request to http://some.url for each file in the array. Here is what I have been attempting: drop.component.ts public drop(event) { ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

TypeScript Interfaces: A Guide to Defining and

In my angular2 application, I have created interfaces for various components. One of these interfaces is specifically for products that are fetched from a remote API. Here is the interface: export interface Product { id: number; name: string; } ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

What is the best way to reset a setInterval ID in Angular?

In my Angular project, I am developing a simple timer functionality that consists of two buttons – one button to start the timer and another to stop it. The timer uses setInterval with a delay of 1000ms. However, when the stop button is pressed, the time ...

How to display a festive greeting on the specific holiday date using the ngx-bootstrap datepicker

Currently, I have implemented the ngx-bootstrap datepicker for managing appointment schedules. I have disabled weekend days and holiday dates, but now there is a requirement to display a tooltip with a holiday message when hovering over a holiday date. htt ...

Tips for selecting an image from the gallery with IONIC 3

Looking for guidance on extracting an image from the gallery in IONIC 3? I attempted to grab an image from the gallery but encountered some issues. Visit this link for more information This resource may also be helpful ...

Although VSCode is functioning properly, there seems to be a discrepancy between the VSCode and the TS compiler, resulting in an

While developing my project in VSCode, I encountered an issue with accessing req.user.name from the Request object for my Node.js Express application. VSCode was indicating that 'name' does not exist in the 'user' object. To address thi ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...

Is it normal that aws-eventbridge-lambda does not generate a Lambda function?

I've been experimenting with the AWS CDK (Typescript) to enhance my knowledge. I'm interested in setting up a lambda function to run daily at a specific time or at intervals of N minutes. Since I anticipate having multiple functions, it would be ...

Properly specifying the data type for a generic type variable within a function in TypeScript

As I work on my express project, I am currently coding a function called route. const morph = (params: Function[]) => (req: Request) => params.map(f => f(req)) const applyTransformers = (transformers: Function[]) => (response: any) => { ...

Prevent Chrome Extension Pop-up from Resetting when Closed

I am completely new to the world of programming, with a special focus on web development. My current project is rather simple - it's a Chrome extension designed for note-taking purposes. This extension creates a pop-up window when the user clicks on i ...

How to control the audio currentTime using Angular 2 component

Here is the HTML code snippet that creates an HTML5 audio element: <audio id ="audio2" controls="controls" autoplay="false" (canplay)="CanPlay($event)"> <source src="http://localhost:51657/Audio/1" type="audio/mp3"> </audio> In the ...

Issue encountered while attempting to utilize the useRef function on a webpage

Is it possible to use the useRef() and componentDidMount() in combination to automatically focus on an input field when a page loads? Below is the code snippet for the page: import React, { Component, useState, useEffect } from "react"; import st ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

What is the reason for a boolean extracted from a union type showing that it is not equivalent to true?

I'm facing a general understanding issue with this problem. While it seems to stem from material-ui, I suspect it's actually more of a typescript issue in general. Despite my attempts, I couldn't replicate the problem with my own types, so I ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Angular 7: Unable to connect with 'messages' because it is not recognized as a valid attribute of 'message-list'

Currently, I am embarking on an Angular journey to develop a hobby chat project using Angular 7 for educational purposes. My main hurdle lies in comprehending modules and components, which has led me to encounter a certain issue. The Challenge In the tut ...