Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First item from a Map on JavaScript ES2015

I have a Map like this:

const m = new Map(); m.set('key1', {}) . m.set('keyN' {}) 

the Mapcan have 1 or many items. Can I get the first item by index, without m.get('key1') and without a iterator loop?

like: m.get()[0]

like image 284
Philip Loger Avatar asked Sep 03 '15 10:09

Philip Loger


People also ask

How do I find the first item on a map?

To get the first element of a Map , use destructuring assignment, e.g. const [firstKey] = map. keys() and const [firstValue] = map. values() . The keys() and values() methods return an iterator object that contains the Map's keys and values.

How do I change the first value on a map?

to get the first key in a map. So to set the first value, use the Map. prototype. set(); method using objects.

Does map in JavaScript maintain insertion order?

The Map object holds key-value pairs and remembers the original insertion order of the keys.

How do I iterate a map in JavaScript?

Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.


2 Answers

Use the Map.prototype.entries function, like this

const m = new Map();  m.set('key1', {})  m.set('keyN', {})    console.log(m.entries().next().value); // [ 'key1', {} ]

If you want to get the first key, then use Map.prototype.keys, like this

console.log(m.keys().next().value); // key1 

Similarly if you want to get the first value, then you can use Map.prototype.values, like this

console.log(m.values().next().value); // {} 

The reason why we have to call next() on the returned values is that, all those functions return iterators. Read more about the iteration protocol here.

like image 80
thefourtheye Avatar answered Oct 13 '22 12:10

thefourtheye


For the specific example you are wondering about, destructuring would be perfect.

let m = new Map(); m.set('key1', {}); m.set('key2', {});  let [[, obj]] = m; 

e.g.

let [pair] = m; let [key, obj] = pair; 

is one option to destructure and then grab the value, but the easier option would be

let [obj] = m.values(); 
like image 25
loganfsmyth Avatar answered Oct 13 '22 11:10

loganfsmyth