Search code examples
javascriptdata-structureslodash

Extend object. Is there any way to assign values when the property is available?


I have an object

        var general = {
            'primary_color': {'value': undefined},
            'logo': {'value': undefined},
        },

When i receive data from server i receive something like this

        var response = {
            'primary_color': {'value': '#DDD'},
            'logo': null,
        },

I wonder if there is any one liner function using will convert my structure as

        var result = {
            'primary_color': {'value': '#DDD'},
            'logo': {'value': undefined},
        },

Solution

  • You can do this with _.mergeWith() by defining which value should be returned, when the current value is null or undefined by using _.isNil():

    var general = { 'primary_color': {'value': undefined}, 'logo': {'value': undefined} };
    var response = { 'primary_color': {'value': '#DDD'}, 'logo': null };
    
    var result = _.mergeWith({}, general, response, function(objValue, srcValue) {
      if(_.isNil(objValue)) {
        return srcValue;
      }
      
      if(_.isNil(srcValue)) {
        return objValue;
      }
    });
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>