兩個結構相同的數組是可以合併的,使用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() 方法即可,但是數組對象的話,比較複雜,不能直接用,我們可以採取間接的方法來去重