Typescript - 如何在地图中设置对象键的值

Typescript - How to set the value of an object key in a Map

我有一个 Map,它以 Lecture 为键,以 Todo 数组为值。

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

现在我先把这个Map的key设置成没有任何值(因为后面会得到Todos)

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

现在我只想将我的 Todos 设置为其特定的 Key。

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

但是此时它总是说“无法读取未定义的属性 'push'”。 我知道我可以完成它,当我使用字符串作为键时,但我想改用我的对象,因为它让我以后的事情变得更容易。

有没有办法让 get-Method 在这个讲座对象上工作?

虽然以后很难从地图中检索元素,但实现您的 objective 的一种方法如下所示。


假设您的类型如下(根据您的要求更改)

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

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

给定数据:

 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' }
  ];

创建地图的逻辑

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) {
        // implies that there is a previous todo added earlier
        this.lecturesWithTodos.set(findLecture, [...findAllTodos, todo]);
      } else if (findLecture) {
        // implies that its a new todo being set
        this.lecturesWithTodos.set(findLecture, [todo]);
      }
  });

}

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

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

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