Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. function mergeDeep(...objects) {
  2.  
  3. // For simplicity, we ignore the cases for Date and Regex
  4. const isObject = obj => obj && typeof obj === 'object';
  5.  
  6. return objects.reduce((prev, obj) => {
  7. try {
  8. Object.keys(obj).forEach(key => {
  9. const pVal = prev[key];
  10. const oVal = obj[key];
  11.  
  12. if (Array.isArray(pVal) && Array.isArray(oVal)) {
  13. prev[key] = pVal.concat(...oVal);
  14. } else if (isObject(pVal) && isObject(oVal)) {
  15. prev[key] = mergeDeep(pVal, oVal);
  16. } else {
  17. prev[key] = oVal;
  18. }
  19. });
  20.  
  21. return prev;
  22. } catch (rangeError) {
  23. if (rangeError instanceof RangeError) {
  24. console.log(rangeError.message);
  25. }
  26. return prev;
  27. }
  28. }, {});
  29. }
  30.  
  31. mergeDeep({a: 1, b: 2}, {c: 3, d: 4}); // {a: 1, b: 2, c: 3, d: 4}
  32. mergeDeep([{a: 1, b: 2}], [{c: 3, d: 4}]); // [{a: 1, b: 2, c: 3, d: 4}]
  33.  
  34. var object = {
  35. y: 2,
  36. };
  37. var other = {};
  38. object.x = other;
  39. other.y = object;
  40. mergeDeep(object, other); // {y: {y: 2, x: {...}}, x: {y: {...}}}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement