0

Imagine i have an array such as:

[obj1, obj2, obj3]

ObjX is something like:

{id:'something',a:1,b:2,...}

How do i convert it to ES6 Map type?

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53

1 Answers1

0

Simply do this:

let firstArray = [obj1, obj2, obj3]
// i randomly selected id to be my Map key, could be any other
let myKeyValueArray = firstArray.map(item=>[item.id,item])
let myMap = new Map(myKeyValueArray)

Reference

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53
  • 1
    Why did you post and answer on your question at the same time... – Alex Mar 27 '19 at 19:28
  • Because i just wasted time searching for this answer. Might help others. – Tiago Bértolo Mar 27 '19 at 19:30
  • 2
    @Alex Self answers are fine [and actually encouraged](https://stackoverflow.com/help/self-answer). – Ivar Mar 27 '19 at 19:30
  • 2
    However, the question needs work in order for the answer to make sense. How would one guess from the question that the map is supposed to be keyed on `id`? – Scott Sauyet Mar 27 '19 at 19:32
  • I second that this question needs to be more clear. – Adnan Sharif Mar 27 '19 at 19:38
  • @ScottSauyet, op could look to the dupe target ... ;-) – Nina Scholz Mar 27 '19 at 19:47
  • @NinaScholz: Yes, but a reader can only get the full scope of the question by looking at the answer. Something wrong there. :-) – Scott Sauyet Mar 27 '19 at 21:35
  • @ScottSauyet Map doesn't need to be keyed on id. This is question is nowhere in Stackoverflow. Added comment to clarify. – Tiago Bértolo Mar 28 '19 at 00:20
  • @ScottSauyet > a reader can only get the full scope of the question by looking at the answer > Question is straight forward. There is nothing else to add. – Tiago Bértolo Mar 28 '19 at 00:26
  • @NinaScholz a reference to ES6 in the question you marked would have enabled me to find it. – Tiago Bértolo Mar 28 '19 at 00:27
  • Well, if you don't care what the key is, you could always do `new Map(Object.entries(myArray))`. :-) My point was that one couldn't answer your question in any helpful way without more information. "How do i convert it to ES6 Map type?" has many legitimate, but incompatible, answers. – Scott Sauyet Mar 28 '19 at 00:48