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

如何从对象数组中提取所需唯一键?寻求最简实现方案

从对象数组提取唯一键并排除指定键的简便实现

这里有几种更简洁高效的实现方式,替代你现有的嵌套循环写法:

方法1:利用Set去重 + 数组方法组合

适合对象键可能不一致的场景,自动去重并过滤排除项:

const data = [{
  "year": "2021",
  "europe": 5,
  "namerica": 2.5,
  "asia": 1
}, {
  "year": "2022",
  "europe": 2.6,
  "namerica": 6.7,
  "asia": 2.2
}, {
  "year": "2023",
  "europe": 4.8,
  "namerica": 1.9,
  "asia": 4.4
}];

const omit = ["year"];

const uniqueLabels = [...new Set(data.flatMap(obj => Object.keys(obj)))]
  .filter(key => !omit.includes(key));

console.log(uniqueLabels); // ['europe', 'namerica', 'asia']
  • flatMap 将所有对象的键平铺为一维数组
  • Set 自动去除重复的键
  • 最后通过filter排除不需要的键

方法2:针对结构一致的对象数组(最优解)

如果能确定数组中所有对象的键完全相同,直接取第一个对象的键过滤即可,效率最高:

const uniqueLabels = Object.keys(data[0]).filter(key => !omit.includes(key));

console.log(uniqueLabels); // ['europe', 'namerica', 'asia']
  • 跳过了遍历所有对象和去重步骤,直接获取目标键

方法3:用reduce收集唯一键

逻辑和你的原代码类似,但用reduce简化了循环结构:

const uniqueLabels = data.reduce((acc, obj) => {
  Object.keys(obj).forEach(key => {
    if (!acc.includes(key) && !omit.includes(key)) {
      acc.push(key);
    }
  });
  return acc;
}, []);

console.log(uniqueLabels); // ['europe', 'namerica', 'asia']
  • 用reduce的累加器acc存储结果,遍历每个对象的键并判断是否添加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:20:28