You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS:如何对比两个对象数组的id与type并筛选差异项

解决方案

问题分析

你需要从arr_b中筛选出两类元素:

  1. id在arr_a中完全不存在的元素
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:03:33