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

如何对比两个对象数组 提取指定键值对生成去重新数组

数组处理实现方案

核心逻辑

  • 基于Map结构做重复条目判断,避免生成重复数据
  • 优先处理带status字段的第一个数组,保证有状态值的条目正确提取
  • 再遍历第二个数组,对未收录的条目做补全,无对应status时自动赋值为空字符串
  • 提取字段时直接重命名为要求的brokerName、statis键名

可运行代码

// 输入的两个对象数组
const firstArr = [ 
  {id: 2, name: "HSBC", status: "YES"},
  {id: 3, name: "Morgan Stanley", status: "Pending"}
];

const secondArr = [
  {id: 1, name: "Deutsche Bank", category: "EQUITIES"},
  {id: 2, name: "HSBC", category: "EQUITIES"},
  {id: 3, name: "Morgan Stanley", category: "EQUITIES"},
  {id: 4, name: "Credit Suisse", category: "EQUITIES"},
];

const recordedNames = new Map();
const targetArr = [];

// 先处理带status的第一组数据
firstArr.forEach(item => {
  if (!recordedNames.has(item.name)) {
    recordedNames.set(item.name, true);
    targetArr.push({
      brokerName: item.name,
      statis: item.status || ''
    });
  }
});

// 补全第二组中未收录的条目
secondArr.forEach(item => {
  if (!recordedNames.has(item.name)) {
    recordedNames.set(item.name, true);
    targetArr.push({
      brokerName: item.name,
      statis: ''
    });
  }
});

输出结果

运行后targetArr的内容完全匹配需求格式:

[
  { brokerName: "HSBC", statis: "YES"},
  { brokerName: "Morgan Stanley", statis: "Pending"},
  { brokerName: "Deutsche Bank", statis: ""},
  { brokerName: "Credit Suisse", statis: ""},
]

内容的提问来源于stack exchange,提问作者Mahesh Bhanudas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:48:19