I have a typescript method which removes hashtags from a string and stores them in an array which is part of a model. The complete string is also added to the model. The model is given a UUID, and I would like to give each of the hashtag array elements their own UUID also. My issue is that UUID of the last array element to be looped over is overwriting the other elements UUIDs, causing them all to be the same. How can I ensure my loop runs without doing this. so that each UUID is in fact unique?
Model:
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;
}
Method:
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;
}
}
Fixed the issue by creating the tag object in the iteration of the loop instead .
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));
}