Mikey Mikey - 3 months ago 8
Javascript Question

Copying properties from one object to another with a condition

Lazy-me is wondering if there a better way to copy the properties in one object (source) over to another object (destination) only if the properties exist in the latter? It does not necessarily have to be using Underscore.

For example,

_.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

Answer

One lazy option is:

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

_.pick filters the source object by using the .keys of the destination object and the result is used for extending the destination object.

If you don't want to modify the original objects just pass an empty object to the _.extend function.

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