Guest User

Untitled

a guest
Jan 17th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. /**
  2. * @description Method to check if an item is an object. Date and Function are considered
  3. * an object, so if you need to exclude those, please update the method accordingly.
  4. * @param item - The item that needs to be checked
  5. * @return {Boolean} Whether or not @item is an object
  6. */
  7. function isObject(item) {
  8. return (item === Object(item) && !Array.isArray(item));
  9. }
  10.  
  11. /**
  12. * @description Method to deeply merge objects, if the same key holds arrays, then these arrays are concatenated and primitive duplicate values removed
  13. * @param {Object} target - The targeted object that needs to be merged with the supplied @sources
  14. * @param {Object} [sources] - The object(s) that need to be merged with the @target
  15. * @return {Object}
  16. */
  17. function deepMerge(target, ...sources) {
  18. if (!sources) {
  19. return target;
  20. }
  21.  
  22. let result = target;
  23.  
  24. if (isObject(result)) {
  25. for (let i = 0, len = sources.length; i < len; i++) {
  26. const elm = sources[i];
  27.  
  28. if (isObject(elm)) {
  29. for (const key in elm) {
  30. if (elm.hasOwnProperty(key)) {
  31. if (isObject(elm[key])) {
  32. if (!result[key] || !isObject(result[key])) {
  33. result[key] = {};
  34. }
  35. deepMerge(result[key], elm[key]);
  36. } else {
  37. if (Array.isArray(result[key]) && Array.isArray(elm[key])) {
  38. result[key] = Array.from(new Set(result[key].concat(elm[key])));
  39. } else {
  40. result[key] = elm[key];
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }
  48.  
  49. return result;
  50. }
Add Comment
Please, Sign In to add comment