Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.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);
}
like image 275
sparty02 Avatar asked Jan 23 '15 07:01

sparty02


People also ask

How do you check if a property of an object exists?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How do you assign a value to an object property?

Object.assign() Method Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.

How does object assign () work?

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

How properties are assign to an object in JavaScript?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.


1 Answers

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 : http://jsbin.com/yiyerosabi/1/edit?js,console

like image 166
ne8il Avatar answered Oct 02 '22 12:10

ne8il