Search code examples
javascriptobjectlodash

Is there a function to only assign properties on a destination if the property exists?


This might be a pipe dream, but I'd love a JavaScript (or lodash?) function that does this:

let obj1 = {
  prop1: 'first thing',
  prop2: 'second thing'
};
let obj2 = {
  prop2: 'overridden second thing',
  prop3: 'and another thing'
};

let result = magicalFunction(obj1, obj2);

// result is { prop1: 'first thing', prop2: 'overridden second thing' }

In other words, I need a version of Object.assign that allows me to specify that I want one object's properties to be the "precedent," and that all properties on the source object(s) that do not occur on the precedent should be ignored.


Solution

  • Yes, you can do it - iterate over Object.keys of the source object, and check if there is a property with the same name on the replacer object - replace if there is, and don't if there isn't:

    let obj1 = {
      prop1: 'first thing',
      prop2: 'second thing'
    };
    let obj2 = {
      prop2: 'overridden second thing',
      prop3: 'and another thing'
    };
    
    let result = magicalFunction(obj1, obj2);
    
    function magicalFunction(source, replacer) {
      let output = {};
      Object.keys(source).forEach(key => output[key] = replacer[key] || source[key]);
      return output;
    }
    
    console.log(result);