Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. const removeKey = (key, {[key]: _, ...rest}) => rest;
  2.  
  3. const getNewObj = toAdd => Array.isArray(toAdd) ? getObj(toAdd) : toAdd
  4.  
  5. const DE_DUPE = (e, i, arr) => arr.indexOf(e) === i
  6.  
  7. const removeEmptyObj = (o) => {
  8. let ignores = [null, undefined, ""],
  9. isNonEmpty = d => !ignores.includes(d) && (typeof(d) !== "object" || Object.keys(d).length)
  10. return JSON.parse(JSON.stringify(o), function(k, v) {
  11. if (isNonEmpty(v))
  12. return v;
  13. });
  14. }
  15. const getDeepMerge = (ogObj, opts={})=> {
  16. const { add, uniq=true, replace=false, removeEmpty=false } = opts
  17.  
  18. const isObject = obj => obj && typeof obj === 'object';
  19. return [ogObj, add].reduce((prev, obj) => {
  20. let _add = {...prev}
  21. Object.keys(obj).forEach(key => {
  22.  
  23. const pVal = _add[key];
  24. const oVal = obj[key];
  25.  
  26. if (Array.isArray(pVal) && Array.isArray(oVal)) {
  27. _add[key] = pVal.concat(...oVal).filter(uniq ? DE_DUPE : null)
  28. if(replace){
  29. _add[key] = oVal }
  30. _add = removeEmpty ? removeKey(key, _add) : _add
  31.  
  32. }
  33. else if (isObject(pVal) && isObject(oVal)) {
  34. _add[key] = getDeepMerge(pVal, {...opts, add:oVal})
  35. if(replace){
  36. _add[key] = oVal
  37. }
  38. }
  39. else {
  40. _add[key] = oVal
  41. }
  42. });
  43. return removeEmptyObj(_add)
  44. }, {});
  45. }
  46. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement