Garrett Garrett - 1 year ago 73
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}
console.log(x) // {a:1}

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

My specific case is using
inside my function:

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

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

Answer Source

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})

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download