Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Map has key (object) not working

I'm having some troubles while checking if a map already has an object as key.

e.g.

const myMap: Map<MyObject1, MyObject2> = new Map<MyObject1, MyObject2>();

I also defined an equals function in MyObject1 class

equals(other: ThreatAgentMgm): boolean {
    return other.id === this.id;
}

but myMap.has(myObject1) is always false. I read theat the has method is based on the === operator, should I define something else in MyObject1 class?

like image 240
1Z10 Avatar asked May 10 '18 13:05

1Z10


1 Answers

Since every JSON object in the end is just a string, I ended up using the JSON.stringify(myObject) as the key of the Map, and a couple of values (MyObject1, MyObject2) as the actual value. This way I'm able to get the desired value in time O(1) while keeping the key object available, without the need of parsing the JSON again or worst, retrieving it from the DB once again.

like image 80
1Z10 Avatar answered Sep 20 '22 13:09

1Z10