What is the best way to generate a unique UUID for every object created within a loop?

I am working on a typescript method that eliminates hashtags from a string and saves them in an array within a model. Each element in the hashtag array is assigned a unique UUID along with the complete string added to the model. However, I am facing an issue where the UUID of the last array element being looped over is replacing the UUIDs of the other elements, making them all the same. How can I ensure that each UUID remains unique during the loop?

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

Answer №1

Solved the problem by instantiating the tag object within the loop iteration.

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

}

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

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Putting text file characters into an array

Having recently started learning C, I am facing a challenge with an assignment. The task is to write a program that takes a file name as a command line argument and then prints the contents of the file. However, instead of displaying the actual text from t ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Angular 2 fails to identify any modifications

Within my template, the links are set to change based on the value of the 'userId' variable. <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo"><img src="../../public/images/logo.png" alt="" /></a> ...

Precise object mapping with Redux and Typescript

In my redux slice, I have defined a MyState interface with the following structure: interface MyState { key1: string, key2: boolean, key3: number, } There is an action named set which has this implementation: set: (state: MyState, action: PayloadAct ...

The ultimate guide to testing the export feature using Karma-Jasmine in Angular4

Hello everyone, I'm new to unit testing with Karma-Jasmine in Angular and I've encountered a problem that I hope you can help me with. I have a .ts file called example.constants.ts which contains a function for generating a random ID. Here is th ...

Initiating the node js service locally

I have been working on a Node.js and Gradle application, but I'm having trouble figuring out how to run it locally. So far, I've done the Gradle build (./gradlew) and NPM run build (compile), with all my dependencies neatly stored in the node_mo ...

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

Angular debounce applied exclusively to user input

In my Angular2 project, I have implemented a reactive form. Within one of my components, I am subscribing to the value changes of a form control with a debounce time of 500ms using the following code: myForm.get("myField").valueChanges.debounceTime(500).s ...

Include a link in the email body without displaying the URL

My concern revolves around displaying a shortened text instead of the full link within an email. When the recipient clicks on "Open Link," they should be redirected to the URL specified. The text "Open Link" must appear in bold. My current development fram ...

The program encountered an issue: it cannot access the property 'invalid' because it is undefined

I have a scenario where I am utilizing nested FormGroup in Angular, with the parent formGroup in the HTML and skills as the nested form. However, during validation, the controls are not being found. Can anyone provide assistance with thi ...

Generating a dynamic SQL Insert statement based on an array object

I am currently working on a Typescript project where I am looking to optimize my Insert function by creating one Insert statement for all the elements in an object, rather than generating multiple Inserts for each array item. Here is the code snippet of m ...

Issue with Firebase CLI preventing deployment of Cloud Functions

I'm currently working on an Angular project, and I'm facing a challenge in deploying a single Firebase function. Here's how my functions directory is structured: https://i.sstatic.net/7h1q2.png When I run the command firebase deploy --only ...

"Error: Unable to locate module - 'electron-is-dev'" in my web development project using electron, typescript, and webpack

I'm currently working on a project using Electron, Typescript, and webpack. I am planning to integrate react.js into the project. However, when I ran "npx webpack" in the terminal, I encountered an error message. The error stated that the "electron- ...

Site breaks down post transition to Angular Universal (SSR)

Apologies in advance for the ambiguous title, I didn't want to make it too lengthy. So here's my issue: I have a confirmation page that appears after the user completes a payment on a third-party gateway (like PayPal). The page redirects back to ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

Find the two numbers within a specific range in an array using jQuery

I have two arrays and I need to check for any duplicate ranges. How can I achieve this? let startingArray = ['1', '6.1', '10', '31','6.2',3]; let endingArray = ['2', '9.9', '30&ap ...

Creating a class and initializing it, then implementing it in other classes within an Angular application

Trying to grasp some angular fundamentals by creating a class structure. Unsure if this is the right approach. export class Cars{ Items:Car[]=[]; constructor() { this.Items = [ { id: "1", name: "Honda" ...

Matching regular expressions without the generation of unnecessary array indexes

An adverse pattern matching leads to an extra array element that goes unused. Suppose there is a file with lines like the following: FILE:abc LENGTH:123 AUTHOR:Bobby FILE:xyz LENGTH:987 AUTHOR:Sabine I need to split these lines into columns while disrega ...

A guide on implementing Angular-DataTable within a TypeScript project

Hey everyone, I'm currently working on a TypeScript and Angular application. To create a data table, I decided to use Angular-DataTable. After creating a sample application using it, I added the following code to my Controller: constructor(protecte ...