Last active
October 27, 2017 11:58
-
-
Save branneman/44777fa62efb4e4e4d54aa5963a97d9a to your computer and use it in GitHub Desktop.
Object.assign, mergeObjectsShallow, mergeObjectsDeep
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
/** | |
* Shallow merge objects | |
*/ | |
function mergeObjectsShallow(target, ...sources) { | |
for (let i = 0; i < sources.length; i++) { | |
const source = sources[i]; | |
for (var prop in source) { | |
if (!source.hasOwnProperty(prop)) continue; | |
target[prop] = source[prop]; | |
} | |
} | |
return target; | |
} | |
/** | |
* Deep merge objects | |
*/ | |
function mergeObjectsDeep(target, ...sources) { | |
for (let i = 0; i < sources.length; i++) { | |
const source = sources[i]; | |
for (const prop in source) { | |
if (!source.hasOwnProperty(prop)) continue; | |
if (source[prop].constructor === Object) { | |
target[prop] = mergeObjectsDeep({}, target[prop], source[prop]); | |
} else { | |
target[prop] = source[prop]; | |
} | |
} | |
} | |
return target; | |
} |
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
/** | |
* Object.assign() example | |
*/ | |
var obj0_a = { aap: 1, noot: 2, mies: 3, wim: { wim1: 100, wim2: 200 } }; | |
var obj0_b = { aap: 10, wim: { wim3: 300 } }; | |
console.log(Object.assign({}, obj0_a, obj0_b)); | |
//=> { aap: 10, noot: 2, mies: 3, wim: { wim3: 300 } } | |
/** | |
* Shallow merge example | |
*/ | |
var obj1_a = { aap: 1, noot: 2, mies: 3, wim: { wim1: 100, wim2: 200 } }; | |
var obj1_b = { aap: 10, wim: { wim3: 300 } }; | |
console.log(mergeObjectsShallow({}, obj1_a, obj1_b)); | |
//=> { aap: 10, noot: 2, mies: 3, wim: { wim3: 300 } } | |
/** | |
* Deep merge example | |
*/ | |
var obj2_a = { aap: 1, noot: 2, mies: 3, wim: { wim1: 100, wim2: 200 } }; | |
var obj2_b = { aap: 10, wim: { wim3: 300 } }; | |
console.log(mergeObjectsDeep({}, obj2_a, obj2_b)); | |
//=> { aap: 10, noot: 2, mies: 3, wim: { wim1: 100, wim2: 200, wim3: 300 } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment