0

I am trying to store values in a JavaScript Map using an object as a key. However I am unable to access them using the get method provided by Map object. This is what I am trying to do -

let map1 = new Map();
map1.set({a: 1}, "valueforobject");
console.log(map1.get({a: 1})); //expected this to print valueforobject but got undefined

When I am logging the map itself however I can the that the value has been stored safely. How do I access this using the get method or any other way appropriate here?

6
  • 2
    knowing the following may help ... {a: 1} !== {a: 1} ... but var a = {a: 1}; a === a; Commented Jul 23, 2021 at 5:37
  • Bravo thank you got what you wrote, in that case how can I store value using an object key in a Map and safely access it later. Or should I not be using it at all in which case what are my alternatives? Commented Jul 23, 2021 at 5:40
  • Oh, I thought that would be obvious if you understood why that comment was relevant ... here it is in a way that's 100% relevant to your code - var a= {a:1}; map1.set(a, "valueforobject");console.log(map1.get(a)); Commented Jul 23, 2021 at 5:43
  • I will actually be constructing the object based on the use case, to fetch the value from the map at a later time. Thats why this would not be useful. Commented Jul 23, 2021 at 5:49
  • 1
    Ok, so a map with an object as the key isn't the appropriate tool - you'll need to use a different way to make the key, or different object altogether - if you're careful, you could use JSON.stringify({a:1}) as the key Commented Jul 23, 2021 at 5:51

1 Answer 1

1

This works. Take a look at the official documentation.

let map1 = new Map();
let keyobj = {a: 1};
map1.set(keyobj, "valueforobject");
console.log(map1.get(keyobj)); 
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.