Advertisement
nodejsdeveloperskh

lodash - merge objects - build object based on array of strings

Dec 4th, 2021
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import * as _ from 'lodash';
  2.  
  3. const requestBody = {
  4.   a: {
  5.     a2: 10,
  6.     c: {
  7.       h1: 5,
  8.     },
  9.   },
  10.   b: 2,
  11. };
  12. const fetchedFromDatabase = {
  13.   a: {
  14.     a2: 100,
  15.     g: {
  16.       f1: 10,
  17.     },
  18.     c: {
  19.       h1: 50,
  20.       h2: 10,
  21.     },
  22.   },
  23.   b: 10,
  24. };
  25. let currentValues = {};
  26. const updatedValues = {};
  27. const flattenUpdatedFieldsSeparatedByDot = flattenObject(requestBody);
  28.  
  29. for (const separatedRequestField in flattenUpdatedFieldsSeparatedByDot) {
  30.   const fetchedFromDatabaseValue = _.get(
  31.     fetchedFromDatabase,
  32.     separatedRequestField
  33.   );
  34.   currentValues = {
  35.     ...currentValues,
  36.   };
  37.   _.set(currentValues, separatedRequestField.split('.'), fetchedFromDatabaseValue)
  38. }
  39.  
  40. console.log(currentValues);
  41. // now _.merge()
  42.  
  43. function flattenObject(value: any): Object {
  44.   let toReturn: any = {};
  45.  
  46.   for (const i in value) {
  47.     if (!value.hasOwnProperty(i)) {
  48.       continue;
  49.     }
  50.  
  51.     if (typeof value[i] == 'object') {
  52.       const flatObject = flattenObject(value[i]);
  53.       for (const x in flatObject) {
  54.         if (!flatObject.hasOwnProperty(x)) continue;
  55.  
  56.         toReturn[i + '.' + x] = flatObject[x];
  57.       }
  58.     } else {
  59.       toReturn[i] = value[i];
  60.     }
  61.   }
  62.   return toReturn;
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement