npm.io
0.0.8 • Published 4 years ago

the-great-flattener

Licence
Unlicense
Version
0.0.8
Deps
0
Size
22 kB
Vulns
0
Weekly
0

The Great Flattener

Recursively flatten deeply nested objects

From...

{
  data: 12345,
  str: "Hello",
  meow: {
    meow: {
      str2: "World!",
      woof: {
        str3: "I'm",
        quack: {
          str3: "quokka"
        },
        duck: [
          {
            str4: 'qqp',
            str5: 'bbb'
          },
          {
            obj: {
              str6: 'tahd',
              str7: 'aoeuidhtns'
            }
          }
        ]
      }
    }
  },
  str4: "here"
}

to

{
  "data": 12345,
  "str": "Hello",
  "str2": "World!",
  "str3": "I'm",
  "str3Copy": "quokka",
  "duck": [
    {
      "str4": "qqp",
      "str5": "bbb"
    },
    {
      "str6": "tahd",
      "str7": "aoeuidhtns"
    }
  ],
  "str4": "here"
}

Usage

flatten(obj)

How It Works

Flatten any object to a single layer; only "primitive" values (non-js-objects) are stored in each key. Duplicate keys are resolved by appending "copy" to the end of the one that were found later.

NOTE - arrays with only 1 item will be flattened; arrays with more than 1 item are preserved, but each member will be flattened.