如何对比两个JavaScript对象数组,获取未被选中的对象?
获取两个对象数组的未选中项
要从data数组里筛选出所有不在choose数组中的对象(也就是示例里的周五项),可以用以下几种简洁的实现方式:
方法一:使用filter + some 直接对比
利用数组的filter方法遍历完整数据集,对每个元素用some检查是否存在于已选中集合中——只要id、deviceID、day这三个唯一标识属性完全匹配,就判定为已选中,反之则保留为未选中项。
// 筛选未选中的项 const unselected = data.filter(item => { return !choose.some(choice => choice.id === item.id && choice.deviceID === item.deviceID && choice.day === item.day ); }); console.log(unselected); // 输出结果:仅包含周五的对象数组
方法二:先构建唯一标识集合(适合大数据量场景)
如果数组元素数量较多,反复用some循环查找效率较低,可以先把已选中项的唯一标识(比如拼接id、deviceID、day成字符串)存入Set集合,再用filter快速判断:
// 构建已选中项的唯一标识集合 const chosenKeys = new Set(choose.map(item => `${item.id}-${item.deviceID}-${item.day}`)); // 筛选未选中项 const unselected = data.filter(item => { const key = `${item.id}-${item.deviceID}-${item.day}`; return !chosenKeys.has(key); }); console.log(unselected);
替换你原有for循环的实现
如果要基于你原来的for循环逻辑修改,可以这样写:
const unselected = []; for(var i=0; i<data.length; i++) { const currentItem = data[i]; let isChosen = false; // 遍历已选中集合检查匹配 for(var j=0; j<choose.length; j++) { const choice = choose[j]; if(choice.id === currentItem.id && choice.deviceID === currentItem.deviceID && choice.day === currentItem.day) { isChosen = true; break; } } if(!isChosen) { unselected.push(currentItem); } } console.log(unselected); // 得到仅含周五的对象数组
内容的提问来源于stack exchange,提问作者HiDayurie Dave
相关产品推荐
相关产品推荐

