Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Added: Sep 13, 2018 2:53 PM
Modified: Sep 13, 2018 2:54 PM
Views: 1
Array|object merge recursive (ES2015/ES6)
  1. /**
  2.  * Simple object check.
  3.  * @param item
  4.  * @returns {boolean}
  5.  */
  6. export function isObject(item) {
  7.   return (item && typeof item === 'object' && !Array.isArray(item));
  8. }
  9.  
  10. /**
  11.  * Deep merge two objects.
  12.  * @param target
  13.  * @param ...sources
  14.  */
  15. export function mergeDeep(target, ...sources) {
  16.   if (!sources.length) return target;
  17.   const source = sources.shift();
  18.  
  19.   if (isObject(target) && isObject(source)) {
  20.     for (const key in source) {
  21.       if (isObject(source[key])) {
  22.         if (!target[key]) Object.assign(target, { [key]: {} });
  23.         mergeDeep(target[key], source[key]);
  24.       } else {
  25.         Object.assign(target, { [key]: source[key] });
  26.       }
  27.     }
  28.   }
  29.  
  30.   return mergeDeep(target, ...sources);
  31. }
  32.  
  33. // Example:
  34. mergeDeep(this, { a: { b: { c: 123 } } });
  35. // or
  36. const merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});  
  37. console.dir(merged); // { a: 1, b: { c: { d: [Object] } } }
  38.