14

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?

10
  • 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)? Commented May 10, 2018 at 14:03
  • 2
    Possible duplicate of How to customize object equality for JavaScript Set which talks about Set and not Map but it's about the same issue: key equality Commented May 10, 2018 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? Commented May 10, 2018 at 14:07
  • 1
    Map in JavaScript is not the same as Map in Java, and neither of those are JSON. 🤷‍♂️ Commented May 10, 2018 at 14:25
  • 1
    Objects in maps are same instance match only. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 24, 2019 at 14:00

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.