javascript - JS merge Array of the Maps to a single Map - Stack Overflow

I have a structure ofArray(4) [Map(1),Map(1),Map(1),Map(1)]All keys are different there.I am trying f

I have a structure of

Array(4) [Map(1),Map(1),Map(1),Map(1)]

All keys are different there. I am trying find the mon way to merge it in one Map.

I know the way for two Maps:

let merged = new Map([...first, ...second])

But for this solution I need more mon way.

I have a structure of

Array(4) [Map(1),Map(1),Map(1),Map(1)]

All keys are different there. I am trying find the mon way to merge it in one Map.

I know the way for two Maps:

let merged = new Map([...first, ...second])

But for this solution I need more mon way.

Share Improve this question asked Jul 16, 2022 at 19:11 Uladzislau KaminskiUladzislau Kaminski 2,2752 gold badges19 silver badges35 bronze badges 2
  • reduce might be a way? – cmgchess Commented Jul 16, 2022 at 19:15
  • @cmgchess it seems flatMap is a more short way, thanks – Uladzislau Kaminski Commented Jul 16, 2022 at 19:23
Add a ment  | 

3 Answers 3

Reset to default 6

You are looking for flatMap:

const arr = [
  new Map([[1, 2]]),
  new Map([[3, 4]]),
];

const merged = arr.flatMap(e => [...e])

console.log(merged)

.map each map to its entries, then flatten the array of arrays of entries to just a single array of entries, then turn that into a Map.

const arr = [
  new Map([[1, 2]]),
  new Map([[3, 4]]),
];

const merged = new Map(
  arr.map(
    map => [...map]
  ).flat()
);
console.log([...merged]);

You can use array#reduce to merge multiple Map.

maps.reduce((r, map) => new Map([...r, ...map]), new Map())

const map1 = new Map();
map1.set('a', 1);
const map2 = new Map();
map2.set('b', 2);
const map3 = new Map();
map3.set('c', 3);

const maps = [map1, map2, map3],
      merged = maps.reduce((r, map) => new Map([...r, ...map]), new Map());
console.log([...merged]);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744299085a4567408.html

相关推荐

  • javascript - JS merge Array of the Maps to a single Map - Stack Overflow

    I have a structure ofArray(4) [Map(1),Map(1),Map(1),Map(1)]All keys are different there.I am trying f

    7天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信