如何对比两个对象数组 提取指定键值对生成去重新数组
数组处理实现方案
核心逻辑
- 基于
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
相关产品推荐
相关产品推荐

