Reputation: 324
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" } ]```
Upvotes: 0
Views: 1131
Reputation: 1601
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);
Upvotes: 2
Reputation: 10746
If you just need to know if a card is selected send a string/number to selectableCards
instead of an object and your function doesn't have to change.
@click="selectableCards(user.UserID)"
OR
@click="selectableCards(user.SuperID)"
If however you need to store the object I would recommend using findIndex
instead of includes
if(this.array.findIndex(temp => {
return temp.Group == x.Group && temp.UserID == x.UserID && temp.SuperID == x.SuperID
})>-1)
...the rest of the code is unchanged
Upvotes: 1