How can i get a value in a javascript map by its key?

The get() method returns a specified element from a Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.

Try it

Syntax

Parameters

key

The key of the element to return from the Map object.

Return value

The element associated with the specified key, or undefined if the key can't be found in the Map object.

Examples

Using get()

const myMap = new Map();
myMap.set('bar', 'foo');

console.log(myMap.get('bar')); // Returns "foo"
console.log(myMap.get('baz')); // Returns undefined

Using get() to retrieve a reference to an object

const arr = [];
const myMap = new Map();
myMap.set('bar', arr);

myMap.get('bar').push('foo');

console.log(arr); // ["foo"]
console.log(myMap.get('bar')); // ["foo"]

Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a WeakMap.

Specifications

Specification
ECMAScript Language Specification
# sec-map.prototype.get

Browser compatibility

BCD tables only load in the browser

See also

I have a JavaScript 'Map' like this one

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');

I want some method to return a key by its value.

let jhonKey = people.getKey('jhon'); // jhonKey should be '1'

How can i get a value in a javascript map by its key?

asked Nov 6, 2017 at 11:13

How can i get a value in a javascript map by its key?

3

You can use a for..of loop to loop directly over the map.entries and get the keys.

function getByValue(map, searchValue) {
  for (let [key, value] of map.entries()) {
    if (value === searchValue)
      return key;
  }
}

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');

console.log(getByValue(people, 'jhon'))
console.log(getByValue(people, 'abdo'))

How can i get a value in a javascript map by its key?

answered Nov 6, 2017 at 11:33

4

You could convert it to an array of entries (using [...people.entries()]) and search for it within that array.

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
    
let jhonKeys = [...people.entries()]
        .filter(({ 1: v }) => v === 'jhon')
        .map(([k]) => k);

console.log(jhonKeys); // if empty, no key found otherwise all found keys.

answered Nov 6, 2017 at 11:17

How can i get a value in a javascript map by its key?

Nina ScholzNina Scholz

360k24 gold badges322 silver badges365 bronze badges

11

Though late and other great answers already exist, still you can give the below "..." and "Array.find" a try:

let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');

function getKey(value) {
  return [...people].find(([key, val]) => val == value)[0]
}

console.log('Jasmein - ', getKey('jasmein'))

console.log('Jhon - ', getKey('jhon'))

How can i get a value in a javascript map by its key?

answered Nov 15, 2018 at 6:39

How can i get a value in a javascript map by its key?

Nitish NarangNitish Narang

3,9641 gold badge14 silver badges21 bronze badges

1

There isn't any direct method for picking out information in this direction, so if all you have is the map you need to loop through the set as suggested by others.

If the map/array/other is large enough that such a loop would be a performance issue and the requirement for a reverse lookup is common within the project, you could implement your own structure using a pair of maps/arrays/other with one as per the current object and the other with the key and value reversed.

That way, the reverse lookup is as efficient as the normal one. Of course, you have more work to do as you need to implement each method that you need as a pass-through to one or both of the underlying objects so if the map is small and/or the reverse lookup is not needed often the scan-via-loop option is likely to be preferable due to being simpler to maintain and possible simpler for the JiT compiler to optimise.

In any case, one thing to be wary of is the possibility that multiple keys could have the same value. If this is possible then when looping through your map you need to decide if you are fine to return one of the possible keys arbitrarily (probably the first one) or if you want to return an array of keys, and if implementing a reverse index for data that could have duplicate values the same issue also needs to be accounted for.

How can i get a value in a javascript map by its key?

answered Nov 6, 2017 at 15:36

How can i get a value in a javascript map by its key?

JavaScript Map and Object

Given a JavaScript Map, I like Nitish's answer:

const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

function getKey(val) {
  return [...map].find(([key, value]) => val === value)[0];
}

console.log(getKey('one'));   // 1
console.log(getKey('two'));   // 2
console.log(getKey('three')); // 3

For a JavaScript object, you could do something like so:

const map = {
  1: 'one',
  2: 'two',
  3: 'three',
};

function getKey(val) {
  return Object.keys(map).find(key => map[key] === val);
}

console.log(getKey('one'));   // 1
console.log(getKey('two'));   // 2
console.log(getKey('three')); // 3

How can i get a value in a javascript map by its key?

answered Dec 16, 2019 at 16:11

Lior ElromLior Elrom

18.4k16 gold badges76 silver badges90 bronze badges

2

One could invert the Map so that the keys are the values and the values are the keys and then lookup the original value as a key. Here's an example:

let myMap = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

let invertedMap = new Map([...myMap.entries()].map(
  ([key, value]) => ([value, key]))
);

console.log(invertedMap.get('one'))
// => 1

answered Feb 24, 2020 at 21:45

IliasTIliasT

3,6551 gold badge21 silver badges25 bronze badges

2

Here is a properly typed Typescript solution that doesn't unnecessarily create an array.

function find_map_value(m: Map, predicate: (v: V) => boolean): [K, V] | undefined {
  for (const [k, v] of m) {
    if (predicate(v)) {
        return [k, v];
    }
  }
  return undefined;
}

If you want all values you can use a generator:

function* find_all_map_values(m: Map, predicate: (v: V) => boolean): Generator<[K, V]> {
  for (const [k, v] of m) {
    if (predicate(v)) {
        yield [k, v];
    }
  }
}

answered May 18, 2021 at 12:11

TimmmmTimmmm

80.9k60 gold badges330 silver badges441 bronze badges

2

Why not simply make use of map's built in iterator prototype/instance reference looking for the target value? Injection into the prototype chain/polyfill inspired solution of sorts makes it universal to ones code:

Map.prototype.getKey = function(targetValue){
  let iterator = this[Symbol.iterator]()
  for (const [key, value] of iterator) {
    if(value === targetValue)
      return key;
  }
}

const people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');

const jhonKey = people.getKey('jhon');
console.log(`The key for 'jhon' is: ${jhonKey}`);

For anyone curious why I added yet another answer. Most of these answers (exception, I like Rajesh's answer, but I added to the prototype chain) are doing a lot of data duplication in the name of finding a value by using the spread operator or even straight up crafting Arrays. Object.keys() mind you is also terribly nonperformant.

Note, I use for..of which iterates on iterables. One could do short hand simply with for(const [key, value] of this){...} if desired.

answered Apr 19, 2021 at 2:04

How can i get a value in a javascript map by its key?

Arthur WeborgArthur Weborg

7,9955 gold badges29 silver badges63 bronze badges

2

My TypeScript version:

const getByValue = (m: Map, searchValue: B):[A, B] | undefined => {
  const l:IterableIterator<[A, B]> = m.entries();
  const a:[A, B][] = Array.from(l);
  return a.find(([_k,v]) => v === searchValue);
}

How can i get a value in a javascript map by its key?

answered Apr 23, 2020 at 16:35

JohnJohn

4,1108 gold badges34 silver badges40 bronze badges

JS:

// Returns keys for all instances
function findAll(obj) {
  return Array.from(items.keys()).map(k => items.get(k) === obj ? k : undefined).filter(k => k);
}

// Returns keys for the first instances
function findFirst(obj) {
  return Array.from(items.keys()).find(k => items.get(k) === obj);
}

Typescript:

protected items = new Map();

public findAll(obj: TObject): Array {
  return Array.from(this.items.keys()).map(k => this.items.get(k) === obj ? k : undefined).filter(k => !!k);
}

public findFirst(obj: TObject): TKey | undefined {
  return Array.from(this.items.keys()).find(k => this.items.get(k) === obj);
}

Explanation:

// Gets the keys as an array
Array.from(this.items.keys())

// Map the keys whose object matches the instance of `obj` to the key itself, undefined otherwise
.map(k => this.items.get(k) === obj ? k : undefined)

// Filter out array elements that are undefined
// (!! is for strict type-checking/readability practices, you can simply use k => k)
.filter(k => !!k)

// Finds the first occurrence of the key for the given object, undefined if not found
.find(k => this.items.get(k) === obj)

answered Nov 30, 2020 at 14:44

How can i get a value in a javascript map by its key?

XpleriaXpleria

5,2545 gold badges52 silver badges63 bronze badges

How do you get a specific value from a Map?

HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Is Map a key value pair?

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

Can JavaScript Map have object as key?

A key of an object must be a string or a symbol, you cannot use an object as a key. An object does not have a property that represents the size of the map.

What value is returned if you attempt a key lookup using the get () method for a key that is not set in a Map object?

get() method takes the key of the element to be returned as an argument and returns the element which is associated with the specified key passed as an argument. If the key passed as an argument is not present in the map, then Map. get() method returns undefined. The Map.