metavoid
2/10/2019 - 9:24 PM

Deep merge JS objects (unlike shallow merge of Object.assign and else)

Deep merge JS objects (unlike shallow merge of Object.assign and else)

//Recursive deep merge JS objects (unlike shallow merge of Object.assign and else)

function deepMerge(target, source) {
            let output = Object.assign({}, target);
            if (this.isObject(target) && this.isObject(source)) {
                Object.keys(source).forEach(key => {
                    if (this.isObject(source[key])) {
                        if (!(key in target))
                            Object.assign(output, {
                                [key]: source[key]
                            });
                        else output[key] = this.deepMerge(target[key], source[key]);
                    } else {
                        Object.assign(output, {
                            [key]: source[key]
                        });
                    }
                });
            }
            return output;
      }