Javascript – _.assign only if property exists in target object


My need is to do something like an _.assign, but only if the target object already has the property being assigned. Think of it like the source objects may have some properties to contribute, but also some properties that I don't want to mix in.

I haven't ever used _.assign's callback mechanism, but tried the following. It 'worked', but it still assigned the property to the dest object (as undefined). I don't want it to assign at all.

_.assign(options, defaults, initial, function (destVal, sourceVal) {
  return typeof destVal == 'undefined' ? undefined : sourceVal;

I wrote the following function to do this, but wondering if lodash already has something baked in that is more elegant.

function softMerge (dest, source) {
    return Object.keys(dest).reduce(function (dest, key) {
      var sourceVal = source[key];

      if (!_.isUndefined(sourceVal)) {
        dest[key] = sourceVal;

      return dest;
    }, dest);

Best Solution

You could take just the keys from the first object

var firstKeys = _.keys(options);

Then take a subset object from the second object, taking only those keys which exist on the first object :

var newDefaults = _.pick(defaults, firstKeys);

Then use that new object as your argument to _.assign :

_.assign(options, newDefaults);

Or in one line :

_.assign(options, _.pick(defaults, _.keys(options)));

Seemed to work when I tested it here :,console