What is flattie?
The flattie npm package is a utility for flattening and unflattening nested objects. It is useful for transforming complex nested structures into simpler key-value pairs and vice versa.
What are flattie's main functionalities?
Flattening Objects
This feature allows you to convert a nested object into a flat object with dot-separated keys.
const flattie = require('flattie');
const nestedObject = { a: { b: { c: 1 } }, d: 2 };
const flatObject = flattie(nestedObject);
console.log(flatObject); // { 'a.b.c': 1, d: 2 }
Unflattening Objects
This feature allows you to convert a flat object with dot-separated keys back into a nested object.
const flattie = require('flattie');
const flatObject = { 'a.b.c': 1, d: 2 };
const nestedObject = flattie.unflatten(flatObject);
console.log(nestedObject); // { a: { b: { c: 1 } }, d: 2 }
Other packages similar to flattie
flat
The 'flat' package provides similar functionality for flattening and unflattening objects. It offers more customization options, such as custom delimiters and safe mode to handle arrays.
flatnest
The 'flatnest' package also provides utilities for flattening and unflattening objects. It is designed to be simple and lightweight, similar to flattie, but with fewer configuration options.
flatten
The 'flatten' package is another alternative for flattening nested objects. It focuses on simplicity and ease of use, similar to flattie, but does not support unflattening.
flat-obj
A tiny (188B) utility to flatten an object with customizable glue
This module squashes a nested object (including its internal Arrays) so that the output is a flat object – AKA, it has a single level of depth. By default, the _
character is used to glue/join layers' keys together. This is customizable, of course.
Finally, any keys with nullish values (null
and undefined
) are not included in the return object.
Install
$ npm install --save flat-obj
Usage
import flatObj from 'flat-obj';
flatObj({
a: 'hi',
b: {
a: null,
b: ['foo', '', null, 'bar'],
d: 'hello',
e: {
a: 'yo',
b: undefined,
c: 'sup',
d: 0,
f: [
{ foo: 123, bar: 123 },
{ foo: 465, bar: 456 },
]
}
},
c: 'world'
});
Note: null
and undefined
values are purged.
API
flatObj(input, [glue])
Returns: Object
Returns a new object with a single level of depth.
Important: An object is always returned despite input
type.
input
Type: Object|Array
The object to flatten.
glue
Type: String
Default: _
A string used to join parent key names to nested child key names.
const foo = { bar: 123 };
flatObj({ foo });
flatObj({ foo }, '.');
Benchmarks
Running on Node.js v10.13.0
Validation:
✔ flat
✔ flatten-object
✔ flat-obj@1.x
✔ flat-obj
Benchmark:
flat x 186,002 ops/sec ±1.28% (89 runs sampled)
flatten-object x 188,715 ops/sec ±0.22% (94 runs sampled)
flat-obj@1.x x 274,414 ops/sec ±1.03% (95 runs sampled)
flat-obj x 363,332 ops/sec ±0.57% (97 runs sampled)
License
MIT © Luke Edwards