两个结构相同的数组是可以合并的,使用es6的reduce方法可以合并两个数组并去重,例子如下:
将一个数组添加到另一个数组中并去重,其中tableData是将要
添加到fatherTablelist的数组,这时建议用es6的reduce方法:
inChildByValue: function(tableData){
if (this.fatherTablelist.length < 1 ) {
this.fatherTablelist = tableData
this.inInnerVisible = false
this.$alert('实施信息新增成功!','信息提示',{
confirmButtonText:'确定',
})
}else {
// 合并两个数组
let resources = [...this.fatherTablelist,...tableData]
// 去重
let temp = {}
resources = resources.reduce((prev,curv) => {
// 若临时对象中有一模一样的item,则什么都不做
if (temp[curv.projImplementInst]&&temp[curv.authObject]){}
else{
temp[curv.projImplementInst] = true
temp[curv.authObject] = true
prev.push(curv)
}
return prev
},[])
console.log('resources',resources)
this.fatherTablelist = resources
this.inInnerVisible = false
}
},
参考教程:点这里
往一个table里面添加一条数据,如果重复则不添加,使用some函数很简单:
let obj = {
staffid:this.multipleSelectionPeoples[0].staffid,
username:this.multipleSelectionPeoples[0].username,
projTabencode:this.multipleSelectionSecrets[0].projTabencode,
projTabcnname:this.multipleSelectionSecrets[0].projTabcnname
}
let len = this.tableData.length
if(len === 0) {
this.tableData.push(obj)
}else {
let res = this.tableData.some(item => {
return item.staffid === obj.staffid && item.projTabencode === obj.projTabencode
})
if(res) {
this.$message({
type: 'warning',
message: '已存在重复数据'
})
} else {
this.tableData.push(obj)
}
}
3.数组对象去重
一般的数组去重可以直接用 new Set() 方法即可,但是数组对象的话,比较复杂,不能直接用,我们可以采取间接的方法来去重