【问题标题】:Typescript - How to set the value of an object key in a MapTypescript - 如何在地图中设置对象键的值
【发布时间】:2025-12-01 13:15:02
【问题描述】:

我有一个地图,它以讲座为键,以待办事项数组为值。

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

现在我先设置这个 Map 的键,不带任何值(因为我稍后会得到 Todos)。

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

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

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

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

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

【问题讨论】:

  • 它如何“让以后的事情变得更容易”?在尝试从地图中检索数据时,您将再次面临确切的问题
  • 确保您使用的是在第一个 forEach 中添加的相同讲座参考
  • 因为当我遍历该地图时,我可以直接获取我的讲座对象的值,而无需额外的讲座数组。我检查了一千次,它们是相同的,但 get-Method 似乎无法识别它
  • 是的,虽然属性相同,但它们是不同的对象,所以.get(..) 不会认为它们相等。
  • 还有其他方法可以设置这个对象键的值吗?

标签: angular typescript dictionary set key


【解决方案1】:

虽然稍后从地图中检索元素会很困难,但下面说明了实现目标的一种方法。


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

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);
}

【讨论】:

    最近更新 更多