[Vuejs]-Vue push unique values to a list

0👍

I would move to storing data in an object (keyed by id) and use a computed property to produce your v1 array. For example

data: {
  v1obj: {}
},
computed: {
  v1 () {
    return Object.keys(this.v1obj).map(id => ({ id, name: this.v1obj[id] }))
  }
}

Then you can use methods like Object.prototype.hasOwnProperty() to check for existing keys…

methods: {
  pushUnique () {
    let id = 1
    let name = 'josh'
    if (!this.v1obj.hasOwnProperty(id)) {
      this.v1obj[id] = name
    }
  }
}

Leave a comment