Faraz
Faraz

Reputation: 6275

How to get the size of keys in map?

Lets say I have this map:

var myMap = new Map();
myMap.set('0', 'foo');
myMap.set(1, 'bar');
myMap.set({}, 'baz');

var size= myMap.keys().size(); // wrong. 

console.log(size); //Looking for 3 because there are 3 keys

Is there a way? Or any alternative? Much appreciated.

Upvotes: 1

Views: 115

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386730

You could read the Map#size property for the count of items.

var myMap = new Map;
myMap.set('0', 'foo');
myMap.set(1, 'bar');
myMap.set({}, 'baz');

var size = myMap.size;

console.log(size); // 3
console.log([...myMap.keys()]); // get all keys

Upvotes: 2

Estus Flask
Estus Flask

Reputation: 222855

keys() returns an iterator of map keys. It should be iterated first and converted to array in order for its length to be known. This is unnecessary, since keys count is equal to entries count, and the latter is already known:

[...myMap.keys()].length === myMap.size

Upvotes: 1

Patrick Hund
Patrick Hund

Reputation: 20246

You can get the size of a map by using its size property:

var size = myMap.size;

Upvotes: 2

bwalshy
bwalshy

Reputation: 1135

You can just do:

var size = myMap.size;

Upvotes: 3

Related Questions