如何为 for 循环中创建的每个对象创建一个单独的 UUID?

How to create a separate UUID for each object created in a for loop?

我有一个打字稿方法,它从字符串中删除主题标签并将它们存储在一个数组中,该数组是模型的一部分。完整的字符串也被添加到模型中。该模型被赋予了一个 UUID,我也想为每个主题标签数组元素提供它们自己的 UUID。我的问题是要循环的最后一个数组元素的 UUID 正在覆盖其他元素的 UUID,导致它们全部相同。如果不这样做,我如何确保我的循环运行。这样每个 UUID 实际上都是唯一的?

型号:

import { UUID } from 'angular2-uuid';

export interface Note {
    id: UUID;
    projectId?: string;
    name?: string;
    img?: File;
    message: string;
    date?: Date;
    tags?: Tags[];
}

export interface Tags {
    id: UUID;
    tag: string;
}

方法:

    notes: Note[] = [];
    tags: Tags[] = [];
    newTags = {} as Tags;
    newNote = {} as Note;

    addNote() {
    this.newNote.id = uuid();
    this.newNote.projectId = this.project.id;
    const regexp = /\B\#\w\w+\b/g;
    const result = this.newNote.message.match(regexp);

    if (result != null) {
      for (let i = 0; i < result.length; i++) {
        this.newTags.tag = result[i];
        this.newTags.id = uuid();
        console.log(this.newTags);
        this.tags[i] = this.newTags;
        this.newNote.tags = this.tags;
     }
  }

通过在循环迭代中创建标签对象解决了这个问题。

addNote() {
   this.newNote.id = uuid();
   this.newNote.projectId = this.project.id;
   const regexp = /\B\#\w\w+\b/g;
   const result = this.newNote.message.match(regexp);

if (result != null) {
  for (let i = 0; i < result.length; i++) {
      var newTag = {} as Tags;
      newTag.tag = result[i];
      newTag.id = uuid();
      console.log(newTag);
      this.tags.push(newTag);
  }
}

this.newNote.tags = this.tags;
this.notes.push(this.newNote);
console.log(this.newNote);
this.noteService.addNote(this.newNote).subscribe(() => {
  this.newNote = {} as Note;
  this.getNotes();

}, error => console.error(error));

}