Vaibhav Patil
Vaibhav Patil

Reputation: 3013

Javascript new Map return reference of the object?

I have a javascript Map

var map1 = new Map();
map1.set('bar',{"foo":"baz"});
var obj = map1.get('bar')

When I change the value of obj the map value also changed

obj.foo = "abc"
console.log(map1.get("bar")) //{"foo":"abc"}

Why is that? and how to stop this behavior? I know we can use the Object.assign() to unlink the reference, but I need to do every time when I get from Map then. Is there any alternative solution of the best way to do it?

Upvotes: 3

Views: 7174

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386728

You could monkey patch get and return always a copy.

var map1 = new Map();

map1.get = function (ref) {
    return function (k) {
        return Object.assign({}, ref.call(this, k));
    };
}(map1.get);

map1.set('bar', { foo: "baz" });
var obj = map1.get('bar');

obj.foo = "abc"
console.log(map1.get("bar"));

Upvotes: 2

Related Questions