flat
Take a nested Javascript object and flatten it, or unflatten an object with delimited keys.
Installation
$ npm install flat
Methods
flatten(original, options)
Flattens the object - it'll return an object one level deep, regardless of how nested the original object was:
var flatten =// {// 'key1.keyA': 'valueI',// 'key2.keyB': 'valueII',// 'key3.a.b.c': 2// }
unflatten(original, options)
Flattening is reversible too, you can call flatten.unflatten()
on an object:
var unflatten = unflatten// {// three: {// levels: {// deep: 42,// nested: true// }// }// }
Options
delimiter
Use a custom delimiter for (un)flattening your objects, instead of .
.
safe
When enabled, both flat
and unflatten
will preserve arrays and their
contents. This is disabled by default.
var flatten =// {// 'this': [// { contains: 'arrays' },// { preserving: {// them: 'for you'// }}// ]// }
object
When enabled, arrays will not be created automatically when calling unflatten, like so:
// hello: {// you: {// 0: 'ipsum',// 1: 'lorem',// },// other: { world: 'foo' }// }
checkLetter
Check for first character of the key and only if it starts with letter then it proceed to flatten.
// '**/.you': 'ipsum',// hello**: {// you: 'lorem',// },// hello: {// other: {// world: 'foo'// }//}
overwrite
When enabled, existing keys in the unflattened object may be overwritten if they cannot hold a newly encountered nested value:
// TRAVIS: {// DIR: '/home/travis/build/kvz/environmental'// }
Without overwrite
set to true
, the TRAVIS
key would already have been set to a string, thus could not accept the nested DIR
element.
This only makes sense on ordered arrays, and since we're overwriting data, should be used with care.
maxDepth
Maximum number of nested objects to flatten.
var flatten =// {// 'key1.keyA': 'valueI',// 'key2.keyB': 'valueII',// 'key3.a': { b: { c: 2 } }// }
Command Line Usage
flat
is also available as a command line tool. You can run it with
npx
:
npx flat foo.json
Or install the flat
command globally:
npm i -g flat && flat foo.json
Accepts a filename as an argument:
flat foo.json
Also accepts JSON on stdin:
cat foo.json | flat