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

如何将TypeScript中Map<string, number>数组扁平化为单个Map?

把Map<string, number>数组扁平化为单个Map的几种方法

嘿,这个需求其实很常见,我来分享几个简单实用的实现方式,顺便聊聊需要注意的细节~

方法一:使用reduce函数(函数式风格)

reduce是处理这种累加场景的绝佳工具,它可以帮我们一步步把数组里的每个Map合并到一个新的Map中:

const mapsArray: Map<string, number>[] = [new Map([['a', 1]]), new Map([['b', 2], ['a', 3]])];

const flattenedMap = mapsArray.reduce((accumulator, currentMap) => {
  // 遍历当前Map的所有键值对,添加到累加器Map里
  currentMap.forEach((value, key) => {
    accumulator.set(key, value);
  });
  return accumulator;
}, new Map<string, number>()); // 初始值是一个空的Map

console.log(flattenedMap); // 结果:Map(2) { 'a' => 3, 'b' => 2 }

关键说明:

  • 当多个子Map存在相同键时,后面的Map里的键值会覆盖前面的(这是Map.set()的默认行为)。
  • 如果需要自定义冲突处理(比如对相同键的值求和),只需要修改set的逻辑就行,比如:
const flattenedMapWithSum = mapsArray.reduce((acc, currentMap) => {
  currentMap.forEach((value, key) => {
    const existingValue = acc.get(key) || 0;
    acc.set(key, existingValue + value);
  });
  return acc;
}, new Map<string, number>());

console.log(flattenedMapWithSum); // 结果:Map(2) { 'a' => 4, 'b' => 2 }

方法二:使用forEach循环(直观易懂)

如果你觉得reduce有点抽象,用两层forEach循环也能轻松实现,逻辑更直白:

const mapsArray: Map<string, number>[] = [new Map([['a', 1]]), new Map([['b', 2], ['a', 3]])];
const flattenedMap = new Map<string, number>();

// 遍历数组里的每个Map
mapsArray.forEach(map => {
  // 遍历当前Map的键值对,添加到目标Map
  map.forEach((value, key) => {
    flattenedMap.set(key, value);
  });
});

console.log(flattenedMap); // 同样得到:Map(2) { 'a' => 3, 'b' => 2 }

这种写法对新手更友好,逻辑一目了然,和reduce的核心逻辑是一致的,只是写法不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:53:14