【发布时间】:2020-08-23 06:26:31
【问题描述】:
我正在尝试从数组中查找并删除一个对象,或者根据它是否已经存在将其推送到数组中。我尝试了 for if 循环和 forEach 循环,但似乎无法破解它。这是我目前所拥有的:
// 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()查找条目。如果索引不是-1,则拼接出来;否则推送新条目。
标签: javascript arrays vue.js