0

I was trying to convert an object which is used for a map purpose, into a proper Map object. I can iterate over the result of Object.keys() and do like

var myData = {"key1":1, "key2":2, "key3":3},    
     myMap = Object.keys(myData).reduce((m,k) => m.set(k,myData[k]) ,new Map());

which does the job. However i gave a try to Object.assign() like

var myData = {"key1":1, "key2":2, "key3":3},
     myMap = Object.assign(new Map(),myData);

which yields a Map with proper key / value pairs yet the size property always show 0. What's going on here and what would be another nice way to make this conversion that i can not think of..? I am open to any ideas from ES6 and beyond.

Redu
  • 25,060
  • 6
  • 56
  • 76
  • When you use `Object.assign`, you're just creating new properties on the `Map` object, not actually storing anything in the map. – Bergi May 04 '16 at 16:24
  • @Bergi He is asking why the size property always zero even the map got created successfully. I think the linked question won't answer this. – Rajaprabhu Aravindasamy May 04 '16 at 16:27
  • @Bergi oops. Sorry I forgot to read your comment fully. – Rajaprabhu Aravindasamy May 04 '16 at 16:28
  • 1
    @RajaprabhuAravindasamy: The dupe answers the title question, and the "and …" part of the question in the post body. One should only ask one question per post :-) So if "*What is going on here?*" is not sufficiently answered by my comment, the OP best should ask a new question. – Bergi May 04 '16 at 16:31
  • @Bergi i am very confused.. how come an iterable object can have several properties and at the same time have a length property with value "zero" – Redu May 04 '16 at 21:18
  • @Redu A map doesn't iterate its properties, it iterates the values stored inside it. It's like you're setting arbitrary properties on an array, only indices are getting iterated (but in contrast to an Array, the keys and values of a Map are not available as properties). – Bergi May 05 '16 at 00:14

0 Answers0