Replace object value without replacing link

How can you update the whole object, say:

var x = {a:1} function modify(obj) { obj = {b:2} } modify(x) console.log(x) // {a:1} 

But keep the link? I want the object to be modified outside the function.

In my specific case, lodash.pick used inside my function:

 if (whitelist) { obj = _.pick(obj, whitelist) } 

I can not find the pick function that modifies the object. Is there a way to do this or do I need to start returning copies of the object?

+5
source share
5 answers

delete everything from the old object, and then add new properties: key-to-key:

 function modify(obj, newObj) { Object.keys(obj).forEach(function(key) { delete obj[key]; }); Object.keys(newObj).forEach(function(key) { obj[key] = newObj[key]; }); } var x = {a:1} modify(x, {b:42}) document.write(JSON.stringify(x)); 

If you're wondering if this is good at all, the answer is no. Create a new object, return it from the function and assign it - this is a very preferred way.

+11
source

You can achieve this (not exactly what you want) if you wrap your object and change the change function like this,

 var wrapper = {}; wrapper.x = {a:1}; function modify(obj, key) { obj[key] = {b:2}; } modify(wrapper, 'x'); console.log(wrapper.x); // {b:2} 
+1
source

I had this problem. After some research, I decided to convert objectTwo to a JSON string, and then replace objectOne with the syntax version. In other words:

 var mObjectOne = { ExampleProperty: 10 }; var mObjectTwo = { ExampleProperty: 15 }; // I wanted mObjectOne to hold the same data as mObjectTwo, but keep a separate reference var mObjectTwoAsJSON = JSON.stringify(mObjectTwo); mObjectOne = JSON.parse(mObjectTwoAsJSON); // Now the references are still different, as desired, but the object data has been updated. 

Thanks,

0
source
 obj = JSON.parse(JSON.stringify(newObj)) 
0
source

Why doesn't the change edit the object referenced by obj?

Since inside change when writing:

 obj = {b:2} 

Note that obj is a local variable for calling the modify function. A new object {b:2} , and the local variable obj now refers to this new object. Recall that the variable x still refers to the object {a:1} .

If x is a global variable AND, if a local variable is not specified inside the function, you can do:

 var x = {a:1}; function modify() { x = {b:2} } modify(); console.log(x) // {b:2} 

Why does this code work?

When you call modify () , it tries to see if it has a local variable x, since it cannot find it, it scans the chain of scopes. The next area to search for this function call is the global area, and, of course, we have the variable x . Therefore, this global variable x is now set.

-2
source

Source: https://habr.com/ru/post/1206980/


All Articles