Search code examples
javascriptnode.jsloopsobjectlodash

Deep Replace values in one object with another object - javascript


Hi i am working with javascript/node.js. I have two data objects. (Please note that the real objects are much more complex than this.)

    const original = {
        'totAmount': 10,
        'testVal': 'zzzzzzzz',
        'potentialPaid': 10,
        'depositAmount': 10,
        'payment': {
            'amount': 10,
             'testVal': 'zzzzzzzz',
            'details': {
                'amount': 10,
                'testVal': 'zzzzzzzz',
                'statusHistory': {
                    'amount': 10,
                    'testVal': 'zzzzzzzz'
                }
            }
        },
        'coupon': {'test': 1000}
    };

and

const dataToUpdate = {
        'totAmount': 65,
        'potentialPaid': 65,
        'depositAmount': 65,
        'payment': {
            'amount': 65,
            'details': {
                'amount': 65,
                'statusHistory': {
                    'amount': 65
                }
            }
        },
        'coupon': {}
    };

I want replace all the values in original from dataToUpdate with the same keys .

My expected result is

    const original = {
        'totAmount': 65,
        'testVal': 'zzzzzzzz',
        'potentialPaid': 65,
        'depositAmount': 65,
        'payment': {
            'amount': 65,
            'testVal': 'zzzzzzzz',
            'details': {
                'amount': 65,
                 'testVal': 'zzzzzzzz',
                'statusHistory': {
                    'amount': 65,
                    'testVal': 'zzzzzzzzz
                }
            }
        },
        'coupon': {}
    };
  • All the values with the same keys in original object should be replaced by the other object values.

I was looking at various solutions like , Object.assign() .merge in lodash and many others.

I am stuck with this for more than 3 hours now and still i cannot find any solution .

Is there any Default javascript function there available doing this kind of a thing ? , please help.

Thanks in advance .


Solution

  • After a bit of research I found that since version 4.0.0 lodash has a mergeWith function that lets you apply a custom criteria for the merge.

    I am adding here a jsfiddle that works for your example but that might need to be adjust a little to cover some other scenarios (I am not sure though).

    The function from the jsfiddle that let you customize the merge criteria is this:

    function customizer(objValue, srcValue) {
      if (_.isEmpty(srcValue)) {
        return srcValue;
      }
      else {
        _.merge(objValue, srcValue);
      }
    }
    

    And here is the jsfiddle:

    http://jsfiddle.net/q9g2L60g/

    I hope this helps.