数组去重
去除引用类型
在这里插入代码片
var arr = [{
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "AAAAAA.doc"
}, {
"name": "ZYTA",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "BBBBBB.doc"
}, {
"name": "ZDTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "CCCCCC.doc"
}, {
"name": "ZYTX",
"age": "Y13xG_4wQnOWK1QwJLgg11d0pS4hewePU95UHtpMl3eE81uS74NC-6zu-Rtnw4Ix",
"gender": "AAAAAA.doc"
}];
var hash = {};
arr = arr.reduce(function(item, next) {
hash[next.name] ? '' : hash[next.name] = true && item.push(next);
return item
}, [])
console.log(arr,'arr');
示例
changeStaf(id,staffCode,canshu) {
if(canshu != 'BJ') {
this.form.staffCode = ''
this.form.staffName = ''
}
this.RobitNameOptions = []
let data = {
page: 0,
size: 9999,
sort: 'desc,name',
orgId: id
}
crudQywxRobotStaff.getStaffList(data).then((res) => {
if (res) {
let newBStaff = res
// this.robotOptions = res.content
var hash = {};
newBStaff = newBStaff.reduce(function (item, next) {
hash[next.id] ? '' : hash[next.id] = true && item.push(next);
return item
}, [])
this.RobitNameOptions = newBStaff
if(canshu ='BJ') {
this.RobitNameOptions.filter((item) => {
if(item.code == staffCode) {
this.form.staffName = item.name
}
})
}
// console.log('各个部门员工',this.RobitNameOptions);
}
}).catch((err) => {
// console.log(err);
})
},
方法二 reduce
元数组
var arrList = [
{id: 1, value: "a"},
{id: 2, value: "b"},
{id: 3, value: "c"},
{id: 4, value: "c"},
{id: 5, value: "a"},
];
我们希望
var arrList = [
{id: 1, value: "a"},
{id: 2, value: "b"},
{id: 3, value: "c"}
];
去重后
let obj = {};
arrList = arrList.reduce((cur,next) => {
obj[next.value] ? "" : obj[next.value] = true && cur.push(next);
return cur;
},[]);
console.log(arrList);
方法三
/**
* 对象数组去重
* @param arr 入参数组
* @param prop 去重属性
* @returns {*}
*/
export function arrUnique(arr, prop) {
if (!prop ||!arr.every(obj => obj.hasOwnProperty(prop))) {
return [];
}
const map = new Map();
return arr.filter(obj =>!map.has(obj[prop]) && map.set(obj[prop], 1));
}