0

I have an array of objects and when I insert a new one I want to know if is duplicate or not.

    this.duplicate = false;

    for(let item of this.items){
        if(item.id && this.item.name === item.name) {  // this.item.name is the value that I try to insert
//item.id (if is add, id = null, is update id = value)
            this.$notify({
                group: "notify",
                text: "Duplicate value! ",
                type: "error"
            });
            this.duplicate = true ;
        }
    }

    if(!this.duplicate){
        // post/put request
    }

This works just for add (post request), on update I get always duplicate value.

2 Answers 2

1

You can check before you add

  const newItem; // comes from request

  const duplicateIndex = this.items
    .map(item => item.name)
    .indexOf(newItem.name);
  // returns index of Object that has same name as newItem's name 
  // or -1 if not found

  // Post request
  if (newItem.id == null) {
    if (duplicateIndex) {
      this.$notify({
        group: "notify",
        text: "Duplicate value! ",
        type: "error"
      });
    } else {
      this.items.push(newItem);
    }
  // Put request
  } else {
    this.items[duplicateIndex] = newItem;
  }
Sign up to request clarification or add additional context in comments.

Comments

0

This might help, Idea is to get the existing Id of record, and match with other records, if other record's id and this id mis-match then you can say this is proper duplicate value

this.duplicate = false;

for(let item of this.items){ 

var existingId=this.item.id || -1; // null coalescing operator (??) is using a logical OR (||):


        
        if (existingId!=item.id && this.item.name.toUpperCase().indexOf(item.name.toUpperCase()) == -1) {
           this.$notify({
                group: "notify",
                text: "Duplicate value! ",
                type: "error"
            });
            this.duplicate = true ;
        } else {
             //nothing found
        }        
    }

    if(!this.duplicate){
        // post/put request
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.