Simoyw
Simoyw

Reputation: 691

How to get value of an object key from a Map

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

Answers (3)

Nina Scholz
Nina Scholz

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

Fanyo SILIADIN
Fanyo SILIADIN

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

Arg0n
Arg0n

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

Related Questions