Reputation: 691
If I add these value on a Map:
var m = new Map();
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set({x:1}, 3);
m.forEach(function (item, key, mapObj) {
document.write(item.toString() + "<br />");
});
document.write("<br />");
document.write(m.get(2));
document.write("<br />");
document.write(m.get({x:1}));
This prints:
black
red
2
3
red
undefined
Why I get undefined
in the last line? And is there a way to retrieve the value of a object key stored in a Map?
Upvotes: 1
Views: 84
Reputation: 386560
You need the object reference for getting the object. Any new literal is a new object, and is different.
var obj = { x: 1 },
m = new Map();
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set(obj, 3);
m.forEach(function (item, key, mapObj) {
console.log(item.toString());
});
console.log(m.get(2));
console.log(m.get(obj));
console.log([...m]);
Upvotes: 2
Reputation: 792
you have undefined simply because
document.write(m.get({x:1}));
the object you are fetching at this line is not the same as the one here
m.set({x:1}, 3);
try this:
var m = new Map();
var obj = {x:1};
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set(obj, 3);
m.forEach(function (item, key, mapObj) {
document.write(item.toString() + "<br />");
});
document.write("<br />");
document.write(m.get(2));
document.write("<br />");
document.write(m.get(obj));
Upvotes: 0
Reputation: 8423
You will probably need a reference to the object:
var m = new Map();
var o = {x:1};
m.set(o, 3);
m.get(o); //3
Upvotes: 2