I'm trying to find and remove an object from an array, or push it to the array based on if it already exists. I've tried a for if loop and forEach loop and can't seem to crack it. Here's what I have so far:
// object in store to be modified
this.sorts = [
{ field: "title", direction: "asc" },
{ field: "value", direction: "asc" }, // remove if exists, add if not
{ field: "quality", direction: "asc" },
];
<button @click="handleCheckbox('value', 'asc')">Value</button>; // example
handleCheckbox(field, dir) {
this.sorts.forEach((field, i) => {
if (this.sorts[i].field === field) {
this.sorts = this.sorts.splice(i, 1); // remove if passed field is found in array
console.log("deleted=", this.sorts[i]);
return;
} else {
this.sorts.push({ field: field, direction: dir }); // add if passed field is not found
console.log("pushed=", this.sorts[i]);
return;
}
});
// state.commit("setSorts", this.sorts);
}
.findIndex()to find the entry. If the index is not -1, then splice it out; otherwise push the new entry.