I'm struggling to manipulate an array by either removing or adding an object based on its existence. I've attempted using both a for if loop and forEach loop but haven't been successful. Here's my current approach:
// Object in store that needs modification
this.sorts = [
{ field: "title", direction: "asc" },
{ field: "value", direction: "asc" }, // Remove if it 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 the field if found in the array
console.log("deleted=", this.sorts[i]);
return;
} else {
this.sorts.push({ field: field, direction: dir }); // Add the field if it's not found
console.log("pushed=", this.sorts[i]);
return;
}
});
// state.commit("setSorts", this.sorts);
}