Last active
February 5, 2020 07:44
-
-
Save yiyizym/9e9484a4a9494e3e712f6223b6419d4f to your computer and use it in GitHub Desktop.
deep_merge
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
'use strict'; | |
function deepMerge(){ | |
let args = [].slice.call(arguments); | |
let target = args.shift(); | |
let sources = args; | |
if(sources.length == 0){ | |
return target; | |
} | |
else { | |
let source = sources.shift(); | |
for(let key in source){ | |
if(!source.hasOwnProperty(key)){ | |
continue; | |
} | |
if(typeof source[key] == 'object'){ | |
if(!target.hasOwnProperty(key)){ | |
target[key] = {} | |
} | |
deepMerge(target[key],source[key]); | |
} | |
else { | |
target[key] = source[key]; | |
} | |
} | |
sources.unshift(target) | |
return deepMerge.apply(null,sources); | |
} | |
} | |
let a = {'a': {'c':3},'d':4} | |
let b = {'a': {'d':4}} | |
let c = deepMerge({},a, b); | |
console.log(c) |
zymiboxpay
commented
Feb 13, 2017
if(typeof source[key] == 'object')
also need to check on null because typeof null === "object"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment