Madhab452 Madhab452 - 1 month ago 14
Javascript Question

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},

Answer Source

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;

<script src=""></script>