Baz
Baz

Reputation: 13125

How do I copy a Map?

I was surprised to find that the following doesn't create an m with size 1:

  let a = new Map();
  a[1] = 2;
  let m = new Map(a);

What should I be doing?

Upvotes: 0

Views: 125

Answers (2)

Quentin
Quentin

Reputation: 943193

The Map is being copied. It just doesn't have any data stored in it.

You need to use the set method to assign a value to a Map. Arbitrary properties are not given special meaning.

let a = new Map();
a.set(1, 2);
let m = new Map(a);

Upvotes: 3

Tomer
Tomer

Reputation: 17930

Map is not an array so it acts a bit differently.

To add an item to a map use:

map.set('key','value')

see more info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Upvotes: 2

Related Questions