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

JavaScript如何遍历含数组的对象并去除重复ID

提取JavaScript对象中唯一ID数组的解决方案

方法1:ES6简洁写法(推荐)

利用Set的自动去重特性,配合Object.values()和flat()快速实现:

const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]};
const ids = [...new Set(Object.values(testobj).flat())];
console.log(ids); // 输出 [295, 681, 15220, 1123]

步骤拆解:

  • Object.values(testobj):提取对象所有值,得到二维数组 [[295, 681, 15220], [295, 681, 1123]]
  • .flat():将二维数组拍平为一维数组,保留所有ID(含重复)
  • new Set(...):通过Set结构自动过滤重复ID
  • [...Set]:将Set转换回普通数组,得到最终结果

方法2:手动遍历(适合新手理解逻辑)

如果想搞清楚底层实现,手动遍历+判断去重:

const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]};
const ids = [];

// 遍历对象中的每个数组
for (const arr of Object.values(testobj)) {
  // 遍历数组中的每个ID
  for (const id of arr) {
    // 仅当ID未在结果数组中时添加
    if (!ids.includes(id)) {
      ids.push(id);
    }
  }
}

console.log(ids); // 输出 [295, 681, 15220, 1123]

这种方式逻辑直观,但数据量大时性能略逊于Set方法(includes为线性查找)。

方法3:reduce合并数组后去重

用reduce替代flat()完成数组合并,再用Set去重:

const testobj = {"100": [295, 681, 15220], "257": [295, 681, 1123]};
const ids = [...new Set(Object.values(testobj).reduce((total, current) => total.concat(current), []))];
console.log(ids); // 输出 [295, 681, 15220, 1123]

reduce的作用是逐个合并所有子数组,最终得到包含所有ID的一维数组,后续步骤和方法1一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:04:58