Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @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;
- }
Add Comment
Please, Sign In to add comment