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

如何在JavaScript中获取带ID的唯一值?

如何从重复对象数组中提取唯一的ID与名称对象数组?

当前我用JavaScript代码只能得到纯值数组:

["Care One", "Care Two"]

但我需要获取包含ID与名称的唯一对象数组:

[
  {"Source_ID": 1, "SourceName_CR": "Care One"},
  {"Source_ID": 2, "SourceName_CR": "Care Two"}
]

我的现有代码如下:

const body = [
  {Field_ID: 1, FieldName_CR: "First Name", Source_ID: 1, SourceName_CR: "Care One"},
  {Field_ID: 2, FieldName_CR: "Last Name", Source_ID: 1, SourceName_CR: "Care One"},
  {Field_ID: 3, FieldName_CR: "Phone", Source_ID: 2, SourceName_CR: "Care Two"},
  {Field_ID: 4, FieldName_CR: "Email", Source_ID: 2, SourceName_CR: "Care Two"},
];
console.log([...new Set(body.map(item => item.SourceName_CR))]);

方法一:利用Map的唯一性去重

借助Map的键唯一性特性,以Source_ID作为键存储目标对象,遍历数组时仅添加未出现过的ID对应的对象,最后将Map的值转为数组:

const body = [
  {Field_ID: 1, FieldName_CR: "First Name", Source_ID: 1, SourceName_CR: "Care One"},
  {Field_ID: 2, FieldName_CR: "Last Name", Source_ID: 1, SourceName_CR: "Care One"},
  {Field_ID: 3, FieldName_CR: "Phone", Source_ID: 2, SourceName_CR: "Care Two"},
  {Field_ID: 4, FieldName_CR: "Email", Source_ID: 2, SourceName_CR: "Care Two"},
];

const uniqueSources = Array.from(
  body.reduce((map, item) => {
    if (!map.has(item.Source_ID)) {
      map.set(item.Source_ID, {
        Source_ID: item.Source_ID,
        SourceName_CR: item.SourceName_CR
      });
    }
    return map;
  }, new Map())
  .values()
);

console.log(uniqueSources);

方法二:用普通对象跟踪已处理ID

用对象记录已经出现过的Source_ID,先过滤出未处理的项,再构造包含目标字段的对象数组:

const body = [
  {Field_ID: 1, FieldName_CR: "First Name", Source_ID: 1, SourceName_CR: "Care One"},
  {Field_ID: 2, FieldName_CR: "Last Name", Source_ID: 1, SourceName_CR: "Care One"},
  {Field_ID: 3, FieldName_CR: "Phone", Source_ID: 2, SourceName_CR: "Care Two"},
  {Field_ID: 4, FieldName_CR: "Email", Source_ID: 2, SourceName_CR: "Care Two"},
];

const seenIds = {};
const uniqueSources = body.filter(item => {
  if (!seenIds[item.Source_ID]) {
    seenIds[item.Source_ID] = true;
    return true;
  }
  return false;
}).map(item => ({
  Source_ID: item.Source_ID,
  SourceName_CR: item.SourceName_CR
}));

console.log(uniqueSources);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:11:29