情景:项目中用到,ElementUI el-table中选择指定项并且删除,顺便记录下
增删操作
两个数组对象去重 实例:
let arr = [{id: 1, name: 'AAA'}, {id: 2, name: 'BBB'}, {id: 3, name: 'CCC'}, {id: 4, name: 'DDD'}]
let arr2 = [{id: 2, name: 'BBB'}, {id: 3, name: 'CCC'}]
let newArr = []
arr2.forEach(item => {
newArr.push(item.id)
})
for (let id of newArr) {
arr = arr.filter(item => {
return id !== item.id
})
}
console.log(arr)
//得到[{id: 1, name: 'AAA'}, {id: 4, name: 'DDD'}]
向数组中添加对象,防止重复
let arr =[{id: 1, name: 'AAA'}, {id: 2, name: 'BBB'}, {id: 3, name: 'CCC'}, {id: 4, name: 'DDD'}]
let arr2 = {id:4,name:'DDD'}
//向arr中添加arr2 假如存在,就不添加
arr = arr.filter(item=>item.id!=4)
arr.push(arr2)
console.log(arr)
//[{id: 1, name: 'AAA'}, {id: 2, name: 'BBB'}, {id: 3, name: 'CCC'}, {id: 4, name: 'DDD'}]
网友评论