daily pastebin goal
66%
SHARE
TWEET

Untitled

a guest Oct 12th, 2018 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. );
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top