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

如何使用Array Map获取数组中键值对的数值(不含键名)

用map方法从键值对数组中提取数值(不保留键名)

原始输入数组

[
   {
      "course_code":"BSEE",
      "total":1
   },
   {
      "course_code":"BSIT",
      "total":3
   },
   {
      "course_code":"BSME",
      "total":0
   }
]

注意点

你期望的输出格式存在JavaScript语法错误——对象不能直接写成{"BSEE", 1}的形式,JS对象必须包含合法的键值对。如果目标是保留两个数值的集合,最合理的方案是将每个对象转换为数组形式。

解决方案代码

// 定义原始数组
const originalArray = [
  { "course_code":"BSEE", "total":1 },
  { "course_code":"BSIT", "total":3 },
  { "course_code":"BSME", "total":0 }
];

// 使用map提取数值,返回数组结构
const resultArray = originalArray.map(item => [item.course_code, item.total]);

console.log(resultArray);

最终输出

[
  ["BSEE", 1],
  ["BSIT", 3],
  ["BSME", 0]
]

补充方案(若需键值映射结构)

如果需要类似“无显式键名”的键值存储,可以用Map类型:

const resultMap = new Map(originalArray.map(item => [item.course_code, item.total]));
// 取值示例:resultMap.get("BSEE") → 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:35:33