JS对比两个球员数组 为全量数组元素添加选中状态status字段
实现方案
核心判断逻辑不要直接对比两个数组里的对象——JS里对象是引用类型,哪怕属性完全一致,直接做相等判断也会返回false,拿唯一标识playerId作为判断依据最稳妥:
- 第一步:提取所有已选中球员的
playerId,存为Set结构,后续做存在性判断的时间复杂度是O(1),比数组遍历查找效率高很多 - 第二步:遍历全量球员数组,保留每个球员的原有属性,追加
status字段,值为当前球员id是否存在于已选中id集合中即可
可直接运行的代码
const all = [ { playerId: '294', firstName: 'MMM' }, { playerId: '295', firstName: 'arkiv' }, { playerId: '296', firstName: 'julio' }, { playerId: '297', firstName: 'sss' }, ]; const selected = [ { playerId: '296', firstName: 'julio' }, { playerId: '297', firstName: 'sss' }, ]; // 预存已选中球员的id集合 const selectedPlayerIds = new Set(selected.map(item => item.playerId)); // 生成带状态的结果数组 const res = all.map(player => ({ ...player, status: selectedPlayerIds.has(player.playerId) }));
常见踩坑点
- 不要直接用
selected.includes(player)判断选中状态:两个独立创建的对象内存地址不同,哪怕属性完全一致,判断结果也永远是false - 生成新对象时建议用展开运算符做浅拷贝,不要直接修改原
all数组里的对象,避免副作用影响其他依赖原数组的逻辑 - 如果球员数据量很大,不要用嵌套双层循环、数组
find每次遍历判断的写法,性能会差很多,预存id到Set的方案更稳定
运行结果
执行上述代码后得到的res结构完全符合预期:
[ { playerId: '294', firstName: 'MMM', status: false }, { playerId: '295', firstName: 'arkiv', status: false }, { playerId: '296', firstName: 'julio', status: true }, { playerId: '297', firstName: 'sss', status: true } ]
内容的提问来源于stack exchange,提问作者Jurgen Tafaj
相关产品推荐
相关产品推荐

