javascript - 查找重复值Vuejs
问题描述
我有一个对象数组,当我插入一个新对象时,我想知道是否重复。
this.duplicate = false;
for(let item of this.items){
if(item.id && this.item.name === item.name) { // this.item.name is the value that I try to insert
//item.id (if is add, id = null, is update id = value)
this.$notify({
group: "notify",
text: "Duplicate value! ",
type: "error"
});
this.duplicate = true ;
}
}
if(!this.duplicate){
// post/put request
}
这仅适用于添加(发布请求),更新时我总是得到重复值。
解决方案
您可以在添加前检查
const newItem; // comes from request
const duplicateIndex = this.items
.map(item => item.name)
.indexOf(newItem.name);
// returns index of Object that has same name as newItem's name
// or -1 if not found
// Post request
if (newItem.id == null) {
if (duplicateIndex) {
this.$notify({
group: "notify",
text: "Duplicate value! ",
type: "error"
});
} else {
this.items.push(newItem);
}
// Put request
} else {
this.items[duplicateIndex] = newItem;
}
推荐阅读
- python - 使用 GitPython 返回给定根路径下的所有存储库
- reactjs - 如何将全局 scss 文件与 css-modules 一起使用?
- function - 如何修复“关闭:(动态)=> 函数'[函数]'中的无效:静态。” 在飞镖
- java - 将输入值添加到现有 Firebase 数据库值 Java?
- powershell - 如何在选择字符串powershell中的匹配行之后提取特定行
- xaml - 使用自动范围时防止点在 SciChart 表面上被截断
- c# - 使用 AzureAD Auth 在 Kubernetes 中的 .NET Core API 上出现 RemoteCertificateNameMismatch 错误
- excel - 使用关于多个条件的公式在 Excel 工作表中过滤
- amazon-web-services - CodeDeploy,在deployment-root文件夹内,长ID含义
- angular - PrimeNG 下拉菜单位于 ConfirmDialog 内,可启用滚动