Copy properties from one object to another with a condition

Lazy-me wonders if there is a better way to copy properties in one object (source) to another object (destination) only if the properties exist in the latter? It is optional to use Underscore.

For instance,

_.mixin({ assign: function (o, destination, source) { for (var property in source) { if (destination.hasOwnProperty(property)) { destination[property] = source[property]; } } return destination; } }); console.log( _().assign({ a: 1, b: 2, d: 3 }, { a: 4, c: 5 }) ) // a: 4, b: 2, d: 3 
+6
source share
2 answers

One lazy option:

 _.extend(a, _.pick(b, _.keys(a))); 

_.pick filters the source object using the .keys target, and the result is used to expand the target.

If you do not want to modify the original objects, just pass the empty object to the _.extend function.

 _.extend({}, a, _.pick(b, _.keys(a))); 
+3
source

Use Object.assign(obj1, obj2); (if properties exist in the latter), which is native in ES6 (underscore.js is not required).

The Object.assign () method is used to copy the values โ€‹โ€‹of all enumerated own properties from one or more source objects to the target object. It will return the target. More info here .

Example:

 var o1 = { a: 1 }; var o2 = { b: 2 }; var o3 = { c: 3 }; var obj = Object.assign(o1, o2, o3); console.log(obj); 

Alternatively use undescore.js

_.extend(destination, *sources)

or

_.extendOwn(destination, *sources)

Detailed information can be found here: http://underscorejs.org/#extend

+4
source

All Articles