Guest User

Untitled

a guest
Oct 12th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. const _ = require('lodash');
  2.  
  3. const flattenObj = obj => _.reduce(
  4. obj,
  5. (accObj, value, key) => {
  6. if (_.isObject(value)) {
  7. _.forEach(
  8. flattenObj(value),
  9. ($value, $key) => {
  10. accObj[`${key}.${$key}`] = $value;
  11. },
  12. );
  13. } else {
  14. accObj[key] = value;
  15. }
  16. return accObj;
  17. },
  18. {},
  19. );
  20.  
  21. console.assert(
  22. flattenObj({
  23. a: {
  24. b: 1,
  25. d: {
  26. l: 3,
  27. k: 4,
  28. },
  29. },
  30. c: 3,
  31. }) ===
  32. {'a.b': 1, 'a.d.l': 3, 'a.d.k': 4, c: 3},
  33. );
Add Comment
Please, Sign In to add comment