这里提供一个小需求,需要将 examid 相同的项合并,并将此项中的 answer 属性值合起来且不重复
具体数据如下:
state = {
arr: [
{ examid: '1052', stb: '1', optionid: '4199', answer: 'A' },
{ examid: '1265', stb: '1', optionid: '5051', answer: 'A' },
{ examid: '970', stb: '1', optionid: '3871', answer: 'A' },
{ examid: '875', stb: '1', optionid: '3491', answer: 'A' },
{ examid: '1174', stb: '1', optionid: '4687', answer: 'A' },
{ examid: '1017', stb: '1', optionid: '4059', answer: 'AB' },
{ examid: '1017', stb: '1', optionid: '4060', answer: 'B' },
{ examid: '1096', stb: '1', optionid: '4375', answer: 'AB' },
{ examid: '1096', stb: '1', optionid: '4376', answer: 'B' },
{ examid: '856', stb: '1', optionid: '3421', answer: 'AB' },
{ examid: '856', stb: '1', optionid: '3422', answer: 'B' },
{ examid: '1059', stb: '1', optionid: '4227', answer: 'AB' },
{ examid: '1059', stb: '1', optionid: '4228', answer: 'B' },
{ examid: '1039', stb: '1', optionid: '4147', answer: 'AB' },
{ examid: '1039', stb: '1', optionid: '4148', answer: 'c' }
]
}
public xxx = ()=>{
console.log(this.state.arr,'arr');
let newObj = {}
let newArr = this.state.arr.reduce((item: any,currentValue) => {
// 先判断是否重复
if (newObj[currentValue.examid]) {
// 重复,则判断 answer 属性中是否已有当前项的 answer 值,通过正则模糊匹配
let answer = currentValue.answer
let reg = new RegExp(answer)
if (!item[newObj[currentValue.examid]-1].answer.match(reg)) {
item[newObj[currentValue.examid]-1] = {...item[newObj[currentValue.examid]-1], answer: item[newObj[currentValue.examid]-1].answer + currentValue.answer}
}
} else {
// 未重复,则将当前项加入到数组中
newObj[currentValue.examid] = item.push(currentValue)
}
return item
},[])
console.log(newArr,'newArr');
}
结果:

更多可参考:
JS数组中 reduce() 方法 数组对象去重: https://blog.youkuaiyun.com/AS_TS/article/details/108060856
JS数组reduce()方法详解及高级技巧: https://blog.youkuaiyun.com/AS_TS/article/details/108060636
前端模糊匹配方式,前端正则模糊匹配: https://blog.youkuaiyun.com/AS_TS/article/details/108056652

本文深入探讨了JavaScript数组中的reduce方法使用技巧,通过实例详细解释如何利用reduce方法实现数组对象去重,特别关注于合并相同examid的项并确保answer属性值不重复。文章提供了完整的代码示例和相关资源链接,帮助读者掌握reduce方法的高级应用。
3139

被折叠的 条评论
为什么被折叠?



