如何将含重复元素的JSON Array转换为带重复计数的唯一JSON Array
去除JSON数组重复元素并统计重复次数
需求:将包含重复元素的JSON数组转换为无重复元素的数组,同时为每个元素新增repeated字段,记录该元素在原数组中的重复次数。
原数组示例
const duplicateJSON = [{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"3",name:"test3"}];
期望输出示例
const uniqueJSON = [{id:"1",name:"test1",repeated:2},{id:"2",name:"test2",repeated:2},{id:"3",name:"test3",repeated:1}];
实现方案(JavaScript)
利用reduce方法遍历数组,结合临时对象统计重复次数,最后将对象值转为数组即可得到结果。
基于指定字段(如id)判断重复
如果确定id是元素的唯一标识,使用以下代码:
const duplicateJSON = [{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"3",name:"test3"}]; const uniqueJSON = Object.values( duplicateJSON.reduce((acc, item) => { const key = item.id; if (!acc[key]) { acc[key] = {...item, repeated: 1}; } else { acc[key].repeated++; } return acc; }, {}) ); console.log(uniqueJSON);
基于全字段判断重复
如果需要严格匹配所有字段来判定元素是否重复,可将判断键改为JSON.stringify(item):
const duplicateJSON = [{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"1",name:"test1"},{id:"2",name:"test2"},{id:"3",name:"test3"}]; const uniqueJSON = Object.values( duplicateJSON.reduce((acc, item) => { const key = JSON.stringify(item); if (!acc[key]) { acc[key] = {...item, repeated: 1}; } else { acc[key].repeated++; } return acc; }, {}) ); console.log(uniqueJSON);
内容的提问来源于stack exchange,提问作者Santu G
相关产品推荐
相关产品推荐

