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

如何将对象数组中的动态国家key提取为新数组

解法思路

先预设所有对象共有的固定属性集合,遍历数组中每一项时,取出当前对象的所有键名,过滤掉固定属性后剩下的就是国家名称键,汇总后即可得到目标数组。该实现兼容单个对象内存在多个国家动态键的场景。

实现代码

const arr1 = [
  {
    id: 1,
    label: 'CA',
    value: 9,
    Canada: 9,
  },
  {
    id: 2,
    label: 'US',
    value: 7,
    'United States': 7,
  },
  {
    id: 3,
    label: 'AU',
    value: 5,
    Australia: 5,
  },
];

// 固定公共键集合,用于过滤非国家键
const fixedKeys = new Set(['id', 'label', 'value']);
const result = arr1.flatMap(item => Object.keys(item).filter(key => !fixedKeys.has(key)));

console.log(result); // 输出:['Canada', 'United States', 'Australia']

简化写法(单对象仅1个国家键场景)

如果确认每个对象内只会存在一个国家名称的动态键,可以简化为:

const fixedKeys = new Set(['id', 'label', 'value']);
const result = arr1.map(item => Object.keys(item).find(key => !fixedKeys.has(key)));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:15:04