0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点#JS对象数组去重

对象数组去重(重复键)

一般情况下对象数组中的对象都有其唯一键,所以不需判断所有属性都相等。

arrDistinctByKey(arr, key){
const temp = new Map(); // 使用Map可以比对多种类型,不限于字符串
return arr.filter((item) => !temp.has(item[key]) && temp.set(item[key], true));
}

// 常用于过滤列表
const list = [{id: 1, name: 'xiaoming'}, {id: 1, name: 'xiaoming'}, {id: 2, name: 'xiaoliang'}];
const newArr = arrDistinctByKey(list, 'id');
// newArr: [{id: 1, name: 'xiaoming'}, {id: 2, name: 'xiaoliang'}]

5. 对象数组取交集(相同键)

``` js
arrIntersectionByKey(arr1, arr2, key) {
const arr2Keys = arr2.map(item => item[key]);
return arr1.filter(item => arr2Keys.includes(item[key]));
}

// 例如找出用户已领券中包含的本次即将发放的立减券,弹窗告知用户已领取其中的某些券
const receivedCoupons = [{ name: '立减券' },{ name: '折扣券' }]; // 已领的券
const welfareCoupons = [{ stockId: '立减券' }]; // 本次要发放的福利券
// 用户已领取的福利券,不再重复发放
arrIntersectionByKey(receivedCoupons,welfareCoupons, 'name');
// [{ name: '立减券' }]

举报

相关推荐

0 条评论