Created
October 25, 2017 15:11
-
-
Save maxp/1bf99c964fa67ea035a494ac8ae78a14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isObject(obj) { | |
return obj !== null && typeof obj === 'object'; | |
} | |
const isArray = Array.isArray; | |
function isPlainObject(obj) { | |
return isObject(obj) && ( | |
obj.constructor === Object // obj = {} | |
|| obj.constructor === undefined // obj = Object.create(null) | |
); | |
} | |
function mergeDeep(target, ...sources){ | |
if (!sources.length) return target; | |
const source = sources.shift(); | |
if (isPlainObject(source) || isArray(source)) { | |
for (const key in source) { | |
if (isPlainObject(source[key]) || isArray(source[key])) { | |
if (isPlainObject(source[key]) && !isPlainObject(target[key])) { | |
target[key] = {}; | |
}else if (isArray(source[key]) && !isArray(target[key])) { | |
target[key] = []; | |
} | |
mergeDeep(target[key], source[key]); | |
} else if (source[key] !== undefined && source[key] !== '') { | |
target[key] = source[key]; | |
} | |
} | |
} | |
return mergeDeep(target, ...sources); | |
} | |
// test... | |
var source = {b:333}; | |
var source2 = {c:32, arr: [33,11]} | |
var n = mergeDeep({a:33}, source, source2); | |
source2.arr[1] = 22; | |
console.log(n.arr); // out: [33, 11] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment