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

如何在对象数组中按name字段去重,移除重复place条目?

按name字段对对象数组去重的解决方案

嘿,我看你之前用全对象序列化的方式做数组去重,现在要改成按name字段过滤、只保留每个name对应第一个条目的需求对吧?其实只需要调整一下findIndex里的判断逻辑就行,不用再对比整个对象的字符串啦。

修改后的实现代码

我们把原来的全对象匹配逻辑,改成只针对name字段做对比:

const things = {
  thing: [
    {"place":"here","name":"stuff"},
    {"place":"there","name":"morestuff"},
    {"place":"there","name":"morestuff"},
    {"place":"herehere","name":"stuff"}
  ]
};

// 按name字段去重,保留每个name第一次出现的对象
const uniqueArrayByName = things.thing.filter((thing, index) => {
  return index === things.thing.findIndex(obj => {
    return obj.name === thing.name; // 仅对比name字段
  });
});

console.log(uniqueArrayByName);

输出结果

运行后会得到你期望的结果:

[
  {"place":"here","name":"stuff"},
  {"place":"there","name":"morestuff"}
]

逻辑说明

  • filter遍历数组中的每个元素,findIndex会返回当前thing.name在数组中第一次出现的索引
  • 如果当前元素的索引和这个首次出现的索引相等,就保留该元素;否则说明是重复的name条目,直接过滤掉
  • 这种方式比全对象序列化更高效,不用处理整个对象的字符串转换,只针对目标字段做对比,逻辑也更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:02:47