oooyaya oooyaya - 3 years ago 178
Javascript Question

Object.assign, values only

I have two objects. One is a source object, and another is a deep copy of the source object. The same keys exist in each, but the deep copy may have different values than the source object. For instance:

{
id: 123,
people: [{
name: "Bob",
age: 50
}, {
name: "Alice",
age: 40
}]
}

and

{
id: 123,
people: [{
name: "Bob",
age: 51 // bob is older now
}, {
name: "Alice",
age: 40
}]
}


Please note that the object is much deeper with many more keys/objects/arrays/values.

I want to apply values (and values only) from the updated copy back on to the source object.

The important piece is that I need to maintain the original reference points of the source object. This means I cannot do any of the following:

sourceObject = updatedCopiedObject;


because it overwrites the source object and breaks references to the source object

Object.assign(sourceObject, updatedCopiedObject);


because, as the docs say:


Properties in the target object will be overwritten by properties in
the sources if they have the same key. Later sources' properties will
similarly overwrite earlier ones.


In other words, it also overwrites the references of the source object.

What I need to do is exactly what Object.assign would do, but NOT overwrite properties - just change the values where properties match.

I don't know of any built in method which will do this in the necessary recursive/deep manner. I can write a method which does, but I wanted to see if there was already a solution to this problem first.

Answer Source

I don't know of any built in method which will do this in the necessary recursive/deep manner. I can write a method which does, but I wanted to see if there was already a solution to this problem first.

No, there is not.

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