Nechemia Hoffmann
Nechemia Hoffmann

Reputation: 2507

How to get the only key-value pair in a Map object?

The language is TypeScript / JavaScript on NodeJS. I have a map that occasionally has only one key. When that is the case, I need to get both the key and the object mapped to it and do some processing with it. The function that is responsible for processing the map doesn't know the what the value of the key is. Therefore, I cannot call get() passing in the key.

Just to clarify the map is an actual Map object.

My question is: How can I retrieve the key and its mapped value when there is only one key in the map and its value is unknown? I'd like to use the entries() method, but it returns an iterator.

if (map.size === 1) {
    let key
    let value
    // how do I populate key and value? 
}

Upvotes: 0

Views: 1161

Answers (3)

blaumeise20
blaumeise20

Reputation: 2220

You can try this:

if (map.size === 1) {
    let keyValuePair = map.entries().next().value; // get next element in generator and it's value
    let key = keyValuePair[0];
    let value = keyValuePair[1];
    // do whatever you want
}

Or if you want a shorter syntax:

if (map.size === 1) {
    let [key, value] = map.entries().next().value;
    // do whatever you want
}

Upvotes: 2

Richard Lucas
Richard Lucas

Reputation: 101

You could use the for... of... structure:

for (var [mapKey, mapValue] of map) {
  key = mapKey;
  value = mapValue;
}

Even if it's only one key, this way you can access it even without knowing what key it is.

The same can be done with the forEach() method...

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370949

Invoking the iterator manually with .next and taking the two resulting values from the array works:

const map = new Map([['foo', 'bar']]);
const [key, value] = map.entries().next().value;
console.log(key, value);

Upvotes: 3

Related Questions