rozhan
rozhan

Reputation: 341

how can i prevent creating new duplicate item in javascript

here is a link to my code https://codesandbox.io/s/strange-bash-0n1bf?file=/src/components/TagEditor.vue I have created a tag input with vue js here I am adding new item by input entry I want to prevent duplicate tag name

addTag (name) {
    if ( this.tags.length < 6 )  {
      this.tags.push({
      id: String(Math.floor(Math.random() * 9)),
      name,
      })
      this.name = ""
    }
  },

hope someone could help me with it

Upvotes: 2

Views: 241

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31371

You can map your tags object array to an array containing only the string names and see if the name is already in use, if this is the case ignore the entry (might still want to clear the input field)


    addTag(name) {
      if(this.tags.map(e => e.name).includes(name)) {
        return;
      }
      if (this.tags.length < 6) {
        this.tags.push({
          id: String(Math.floor(Math.random() * 999999999)),
          name,
        });
        this.name = "";
      }
    },

Codesandbox

Upvotes: 2

Related Questions