Make v-card selectable/toggle-able and pass an object to an array in Vue

Yewla :

I currently have some cards that each hold a value. I want to basically make each card act like a toggle button and when the card is toggled on I want that cards value to be added to the array.

I currently use:

@click="selectableCards( {Group: `${user.GroupHex}`, UserID: user.UserIDInt, SuperID: `${user.SuperID}`} )"

to pass the data to my function:

selectableCards(x) {
      if(this.array.includes(x)) {

        console.log('prop already exists inside array')

      } else {

       this.array.push(x)

      }
        console.log(this.array)
    }

Whenever I use this the object is added to the array but it will allow me to add the same object over and over again. It doesn't detect that the object is already in the array.

So again basically I want the @click on the card to act like a toggle button to add or remove the data inside the card.

An example of 3 cards values into an array:

[ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ]```
Mischa :

You cannot cannot compare objects same way as primitives in javascript:

const objects = [ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ]

console.log(objects.includes({ "Group": "10", "UserID": 6, "SuperID": "2566" }))

For more information about that take a look here: Object comparison in JavaScript

However what you can do is to search for an element in an array based on some conditions for example with array.find() -method like so:

const objects = [ { "Group": "10", "UserID": 6, "SuperID": "2566" }, { "Group": "10", "UserID": 5, "SuperID": "2565" }, { "Group": "20", "UserID": 9, "SuperID": "5129" } ];

const matchedObject = objects.find((object) => {
  return object.Group === "10" &&
    object.UserID === 6 && 
    object.SuperID === "2566"
});

console.log(matchedObject);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220417&siteId=1