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

如何用Lodash从嵌套对象数组中提取唯一操作项数组?

提取唯一操作对象的最优实现

嘿,这个需求我经常碰到,给你分享个高效又好维护的实现方案~

首先先明确你的原始数据:

const operationGroups = [ 
  { id: 'id-1', uniqueName: 'operation-level-1', operations: [ 
    { name: 'operaion-1', label: 'operation-1-label' }, 
    { name: 'operaion-2', label: 'operation-2-label' } 
  ] }, 
  { id: 'id-2', uniqueName: 'operation-level-2', operations: [ 
    { name: 'operaion-1', label: 'operation-1-label' }, 
    { name: 'operaion-3', label: 'operation-3-label' } 
  ] } 
];

最优实现(时间复杂度O(n))

这里用flatMap扁平化嵌套数组,结合Map来确保操作的唯一性,是效率最高的方式之一:

// 用Map存储唯一操作,以name作为唯一标识键
const uniqueOpsMap = new Map();

// 先扁平化所有操作数组,再遍历处理
operationGroups.flatMap(group => group.operations).forEach(op => {
  // 只保留第一次出现的相同name的操作
  if (!uniqueOpsMap.has(op.name)) {
    uniqueOpsMap.set(op.name, op);
  }
});

// 把Map的值转为数组就是最终结果
const result = Array.from(uniqueOpsMap.values());

如果你喜欢更紧凑的链式写法,也可以用reduce替代forEach:

const result = Array.from(
  operationGroups
    .flatMap(group => group.operations)
    .reduce((map, op) => {
      // 同样只保留第一次出现的操作,若要保留最后一次则直接set即可
      if (!map.has(op.name)) map.set(op.name, op);
      return map;
    }, new Map())
    .values()
);

为什么这是最优的?

  • 效率高:flatMap是单次遍历完成扁平化,Map的查找和插入都是O(1),整体时间复杂度是O(n)(n是所有操作的总数),大数据量下优势明显
  • 易维护:逻辑清晰,如果之后需要修改去重规则(比如按name+label组合去重),只需要调整Map的键即可,比如改成map.set(${op.name}-${op.label}, op)
  • 灵活性强:可以轻松调整是保留第一次出现的操作,还是最后一次出现的(后者只需去掉has判断,直接set即可)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:57:54