'How to merge nested objects in javascript

Merging nested objects it overides.

let target = { cache: 
              {curUser:
               { callingName: 'ch sairam', dateOfBirth: undefined, isTempDob: true, knowMarketPrefChange: true, email: '[email protected]', gender: '',  livingIn: 'IN', uid: 'CrzpFL2uboaeGvMxXi5WQKSQsCr1', timeZone: undefined }, 
               names: [ [Object] ],   minPrice: '2500', maxPrice: '50000', market: 'CA', foundLovedOne: false,  }
             }
let source = { cache: 
              {curUser: 
               { isTempDob: true, knowMarketPrefChange: false, timeZone: 'Asia/Kolkata' },
               prefLanguage: 'en', market: 'IN',  minPrice: 2250, maxPrice: 45000, foundLovedOne: false, domainName: 'roo-fire.appspot.com', prodQueryPageNumber: 0, welcomeIntentShown: true }, 
              curContexts: [] }
 target = Object.assign({},target,source);

when print target it results

Object { cache: Object { curUser: Object { isTempDob: true, knowMarketPrefChange: false, timeZone: "Asia/Kolkata" }, prefLanguage: "en", market: "IN",   minPrice: 2250, maxPrice: 45000, foundLovedOne: false,  prodQueryPageNumber: 0, welcomeIntentShown: true }, curContexts: Array [] }

source override target, I want to get this results?

{ cache: 
              {curUser:
               { callingName: 'ch sairam', dateOfBirth: undefined, isTempDob: true, knowMarketPrefChange: false, email: '[email protected]', gender: '', prefMarket: 'CA', livingIn: 'IN', uid: 'CrzpFL2uboaeGvMxXi5WQKSQsCr1', timeZone:'Asia/Kolkata' }, 
               prefLanguage: 'en',names: [ [Object] ], minPrice: '2250', maxPrice: '45000', market: 'CA', foundLovedOne: false, prodQueryPageNumber: 0, welcomeIntentShown: true },
              curContexts: [] }


Solution 1:[1]

You could merge all propeties and use a recursive aproach for nested objects.

function merge(a, b) {
    return Object.entries(b).reduce((o, [k, v]) => {
        o[k] = v && typeof v === 'object'
            ? merge(o[k] = o[k] || (Array.isArray(v) ? [] : {}), v)
            : v;
        return o;
    }, a);
}

var target = { cache: { curUser: { callingName: 'ch sairam', dateOfBirth: undefined, isTempDob: true, knowMarketPrefChange: true, email: '[email protected]', gender: '', livingIn: 'IN', uid: 'CrzpFL2uboaeGvMxXi5WQKSQsCr1', timeZone: undefined }, names: [['Object']], minPrice: '2500', maxPrice: '50000', market: 'CA', foundLovedOne: false } },
    source = { cache: { curUser: { isTempDob: true, knowMarketPrefChange: false, timeZone: 'Asia/Kolkata' }, prefLanguage: 'en', market: 'IN', minPrice: 2250, maxPrice: 45000, foundLovedOne: false, domainName: 'roo-fire.appspot.com', prodQueryPageNumber: 0, welcomeIntentShown: true }, curContexts: [] };

console.log([{}, target, source].reduce(merge));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Solution 2:[2]

Object.assign doesn't do a deep merge. To do a nested merge, I suggest using lodash

import _ = require('lodash');
target = _.merge(source, value2);

Alternately, you can copy both the objects and do an object.assign merge

target =Object.assign({},JSON.parse(JSON.stringify(source)), JSON.parse(JSON.stringify(target)))

Solution 3:[3]

You could also use Ramda. it's an open source javascript util. which has much less deps that loadash.

And with Ramda, using the mergeDeepRight :

import { mergeDeepRight } from 'ramda';

result = mergeDeepRight(sourceObject, targetObject)

Object assign doesn't take nested values. which is the issue that you having at this moment.

Solution 4:[4]

You can use this advanced function for object/array deep merge (or deep assign). It's working like a charm.

export function deepAssignJSON(target, source, {isMutatingOk = false, isStrictlySafe = false} = {}) {

    // Returns a deep merge of source into target. Does not mutate target unless isMutatingOk = true.
    target = isMutatingOk ? target : clone(target, isStrictlySafe);
    for (const [key, val] of Object.entries(source)) {
        if (val !== null && typeof val === `object`) {
            if (target[key] === undefined) {
                target[key] = {};
            }

            // Even where isMutatingOk = false,
            // recursive calls only work on clones, so they can always safely mutate --- saves unnecessary cloning
            target[key] = deepAssignJSON(target[key], val, {isMutatingOk: true, isStrictlySafe});
        } else {
            target[key] = val;
        }
    }
    return target;
}

function clone(obj, isStrictlySafe = false) {

    // Clones an object. First attempt is safe. If it errors (e.g. from a circular reference),
    // 'isStrictlySafe' determines if error is thrown or an unsafe clone is returned. 
    try {
        return JSON.parse(JSON.stringify(obj));
    } catch(err) {
        if (isStrictlySafe) { throw new Error() }
        console.warn(`Unsafe clone of object`, obj);
        return {...obj};
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SoWhat
Solution 3 Ido Bleicher
Solution 4 Kamran Taghaddos