How to get map element by key object?

Issue

Thereis a code:

let a = new Map<{id: number, age: number}, string>();

a.set({id: 1, age: 20}, "1");

console.log(a.get({id:1, age: 20}));

It gives me undefined because object added to map and looking object are not equals. Is it possible to make complicate key in map to retrive it when?

I can do this:

  let a = new Map<string, string>();

Where string key is concatination: id_age, but I dislike this, because it is not obviously

Solution

Objects work by reference, and not by value. That means that { a: 5, b: 6 } !== { a: 5, b: 6 }

What you can do is create a class that has a custom equals method that compares properties by value, instead of the object key you currently have:

export default class Person {
  public id: number;
  public age: number;
  
  constructor(id: number, age: number) {
    this.id = id;
    this.age = age;
  }

  public equals(obj: any): boolean {
    return obj && typeof obj === 'object' && obj.id === this.id && obj.age === this.age;
  } 
} 

And then use it in your Map:

const map = new Map<Person, string>();

map.set(new Person(1, 20), '1');
console.log(map.get(new Person(1, 20)); // '1'

Answered By – Eldar B.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published