Created
January 9, 2018 02:44
-
-
Save mir4ef/21eac553bddaa39fb54f7c9ab1758ae3 to your computer and use it in GitHub Desktop.
Deep Merge JavaScript Objects
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
/** | |
* @description Method to check if an item is an object. Date and Function are considered | |
* an object, so if you need to exclude those, please update the method accordingly. | |
* @param item - The item that needs to be checked | |
* @return {Boolean} Whether or not @item is an object | |
*/ | |
function isObject(item) { | |
return (item === Object(item) && !Array.isArray(item)); | |
} | |
/** | |
* @description Method to deeply merge objects, if the same key holds arrays, then these arrays are concatenated and primitive duplicate values removed | |
* @param {Object} target - The targeted object that needs to be merged with the supplied @sources | |
* @param {Object} [sources] - The object(s) that need to be merged with the @target | |
* @return {Object} | |
*/ | |
function deepMerge(target, ...sources) { | |
if (!sources) { | |
return target; | |
} | |
let result = target; | |
if (isObject(result)) { | |
for (let i = 0, len = sources.length; i < len; i++) { | |
const elm = sources[i]; | |
if (isObject(elm)) { | |
for (const key in elm) { | |
if (elm.hasOwnProperty(key)) { | |
if (isObject(elm[key])) { | |
if (!result[key] || !isObject(result[key])) { | |
result[key] = {}; | |
} | |
deepMerge(result[key], elm[key]); | |
} else { | |
if (Array.isArray(result[key]) && Array.isArray(elm[key])) { | |
result[key] = Array.from(new Set(result[key].concat(elm[key]))); | |
} else { | |
result[key] = elm[key]; | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment