React JS:如何对比两个对象数组的id与type并筛选差异项
解决方案
问题分析
你需要从arr_b中筛选出两类元素:
id在arr_a中完全不存在的元素id存在于arr_a,但type字段和arr_a中对应元素不同的元素
你之前的代码有两个核心问题:
- 字段名错误:误写为
action_type,但你的对象实际字段是type - 逻辑方向反了:你筛选的是
arr_b与arr_a中id+type完全匹配的元素,而你需要的是不匹配的元素
优化实现代码
推荐用Map存储arr_a的id-type映射,查询效率更高:
var arr_a = [ { id: 1, name: "thumbler", type: "add" }, { id: 2, name: "spoon", type: "add" }, { id: 3, name: "plate", type: "add" }, ]; var arr_b = [ { id: 1, name: "thumbler", type: "remove" }, { id: 2, name: "spoon", type: "add" }, { id: 3, name: "plate", type: "add" }, { id: 4, name: "fork", type: "add" }, ]; // 构建arr_a的id到type的映射表 const aIdToType = new Map(arr_a.map(item => [item.id, item.type])); // 过滤arr_b得到目标数组 const arr_c = arr_b.filter(item => { const targetType = aIdToType.get(item.id); // 保留两种情况:id不在arr_a中,或者id存在但type不同 return targetType === undefined || targetType !== item.type; }); console.log(arr_c); // 输出结果: // [ // { id: 1, name: "thumbler", type: "remove" }, // { id: 4, name: "fork", type: "add" } // ]
另一种实现(用Set)
如果偏好字符串组合的方式,也可以用Set存储id-type的唯一标识:
const aIdTypeSet = new Set(arr_a.map(item => `${item.id}-${item.type}`)); const arr_c = arr_b.filter(item => { const key = `${item.id}-${item.type}`; // 检查arr_a中是否存在相同id const hasSameId = arr_a.some(y => y.id === item.id); // 要么id不存在,要么id存在但type组合不匹配 return !hasSameId || !aIdTypeSet.has(key); });
内容的提问来源于stack exchange,提问作者Febry Fairuz
相关产品推荐
相关产品推荐

