Garrett Garrett - 24 days ago 6
Javascript Question

Replace object value without replacing reference

How can you update an entire object, say:

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


But maintain the reference? I want the object to be modified outside the function.

My specific case is using
lodash.pick
inside my function:

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


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

Answer

delete everything from the old object, and then add new properties, key-by-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 whether it's a good idea in general, the answer is no. Construct a new object, return it from the function and assign - this is a much preferred way.