首页 > 解决方案 > 查找重复值Vuejs

问题描述

我有一个对象数组,当我插入一个新对象时,我想知道是否重复。

    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
    }

这仅适用于添加(发布请求),更新时我总是得到重复值。

标签: javascriptvue.jsvuejs2

解决方案


您可以在添加前检查

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

推荐阅读