10

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?

1Z10
  • 1,672
  • 2
  • 15
  • 48
  • JavaScript doesn't use any `equals()` method when comparing objects for equality. Why don't you just make your map key the `id` field of `MyObject1` and then do `myMap.has(myObject1.id)`? – jcalz May 10 '18 at 14:03
  • 2
    Possible duplicate of [How to customize object equality for JavaScript Set](https://stackoverflow.com/questions/29759480/how-to-customize-object-equality-for-javascript-set) which talks about `Set` and not `Map` but it's about the same issue: key equality – jcalz May 10 '18 at 14:06
  • I'll need to pass this map as it is to another existing Java API, which will parse this JSON. So what are you saying is that it's not possible to use an object as a key for a map? Am I right? – 1Z10 May 10 '18 at 14:07
  • Do you really mean "Java"? And JSON only allows string keys. Not sure what you're asking. – jcalz May 10 '18 at 14:08
  • You can use an object as a key for a map, but you need to index by the same exact object. If this doesn't meet your needs you can implement your own `Map`-like thing that accepts a key equality function. But I don't understand your use case enough to give a more concrete suggestion. If you want more information please update your question with more details and someone can help. – jcalz May 10 '18 at 14:12
  • Yes, I mean the Java API expects a JSON having MyObject1 stringified as the key of the object. So I'd need to be able to use an object as the key of the map. Strange it's not possible such a simple thing as it is in Java. – 1Z10 May 10 '18 at 14:13
  • Well, the object has the same values, just it's a different instance in time. – 1Z10 May 10 '18 at 14:15
  • 1
    `Map` in JavaScript is not the same as `Map` in Java, and neither of those are JSON. ‍♂️ – jcalz May 10 '18 at 14:25
  • You can still use the stringified object as key. – Paleo May 10 '18 at 17:20
  • 1
    Objects in maps are same instance match only. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – Tezra Oct 24 '19 at 14:00

1 Answers1

5

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.

1Z10
  • 1,672
  • 2
  • 15
  • 48