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

使用Lodash按条件去除对象数组中的重复项

Lodash 实现按ID去重并保留含canvas路径的对象

给定对象数组:

[
    {id:1,name:'abc',path:'canvas.abc'},
    {id:1,name:'abc',path:'public.abc'},
    {id:2,name:'def',path:'supply.def'},
    {id:3,name:'xyz',path:'package.xyz'}
]

要实现按ID去重且优先保留path包含canvas的对象,仅用Lodash可以通过groupBy+map+find的组合完成:

const _ = require('lodash');

const originalArray = [
    {id:1,name:'abc',path:'canvas.abc'},
    {id:1,name:'abc',path:'public.abc'},
    {id:2,name:'def',path:'supply.def'},
    {id:3,name:'xyz',path:'package.xyz'}
];

const result = _.map(_.groupBy(originalArray, 'id'), group => {
    // 优先查找分组内path包含canvas的对象
    const targetItem = _.find(group, item => _.includes(item.path, 'canvas'));
    // 找到就留它,没找到就取分组第一个元素
    return targetItem || group[0];
});

console.log(result);

逻辑说明

  • _.groupBy先把数组按id分组,相同ID的对象会被归为一组
  • 遍历每个分组时,用_.find精准定位组内符合path含canvas的对象
  • 确保每个ID仅保留一个对象,且优先保留符合路径要求的项

运行后输出结果:

[
    {id:1,name:'abc',path:'canvas.abc'},
    {id:2,name:'def',path:'supply.def'},
    {id:3,name:'xyz',path:'package.xyz'}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:34:59