在JavaScript开发中,后端接口经常返回包含重复对象的数组,比如用户列表中出现多条id相同的记录。使用ES6语法可以用很少的代码实现数组对象去重,既清晰又高效。

为什么不能直接用Set去重
普通Set只能判断基本类型值是否相等,而对象是引用类型,即使内容相同也是不同的引用,所以new Set(arr)无法对数组对象去重。我们需要根据对象的某个字段来识别重复。
使用Map实现按字段去重
以下示例以对象的id字段作为唯一标识,利用Map记录已存在的id,过滤出非重复对象:
const arr = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 1, name: '张三' },
{ id: 3, name: '王五' }
];
// 使用Map按id去重
function uniqueByMap(list) {
const map = new Map();
return list.filter(item => {
if (map.has(item.id)) {
return false;
}
map.set(item.id, true);
return true;
});
}
const result = uniqueByMap(arr);
console.log(result);
// 输出: [{id:1,name:'张三'},{id:2,name:'李四'},{id:3,name:'王五'}]
使用reduce与Map结合
也可以用reduce配合Map写出更函数式的写法:
const arr = [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 1, name: '苹果' }
];
const unique = arr.reduce((map, item) => {
if (!map.has(item.id)) {
map.set(item.id, item);
}
return map;
}, new Map());
const result = Array.from(unique.values());
console.log(result);
多字段联合去重
如果需要根据多个字段判断重复,可以把字段拼接成键:
const list = [
{ type: 'a', value: 1 },
{ type: 'b', value: 2 },
{ type: 'a', value: 1 }
];
const seen = new Set();
const result = list.filter(item => {
const key = item.type + '_' + item.value;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
console.log(result);
小结
ES6的Map和Set让数组对象去重变得直观。核心思路是选取能代表对象的唯一键,用Map或Set记录已出现过的键,再通过filter或reduce筛选出唯一数据。实际项目中建议封装成通用函数,根据业务传入键生成规则即可。
JavaScript数组对象去重ES6MapSet修改时间:2026-07-24 20:48:16