flatted-object
v0.1.2
Published
Module to flatten objects like a pro, with guarantees to avoid losing data in the process.
Downloads
13
Maintainers
Readme
Why?
Flattening objects is somewhat difficult as they could have infinitely many nested levels and some of those levels could be array and even other objects.
This module flattens an object to it's "flattest" size possible while still avoiding collapsing none related keys so that data integrity is maintained.
Why the name?
I love the flatted module and I wanted something that's equally fast and at the same time safe to use. Besides, "flatten-object" was already taken by another module which I didn't like much.
How?
Install yarn add flatted-object
then:
const flatted = require('flatted-object');
let obj = {
city: {
library: {
books: [{
name: "How to flatten objects like a pro",
author: {
first: "Anthony",
second: "Mugendi"
}
},
{
name: "How to flatten objects like a pro",
author: {
first: "Anthony",
second: "Mugendi"
}
}
]
}
}
}
// adding cyclic data
obj.obj = obj;
// use without depthMaps
let flattenedObj = flatted(obj);
console.log(JSON.stringify(flattenedObj, 0, 4));
This will log a flattened object as shown below:
{
"city": [
{
"name": "How to flatten objects like a pro",
"author": {
"first": "Anthony",
"second": "Mugendi"
}
},
{
"name": "How to flatten objects like a pro",
"author": {
"first": "Anthony",
"second": "Mugendi"
}
}
],
"obj": "CIRCULAR <obj>"
}
NOTE: There is no way to deal with circular references so they are indicated as "CIRCULAR".
Api
flatten(object, [rootKey]);
You can also pass an alternative rootKey that will be used as the root for the flattened object. Below is an example using the same object above.
...
flattenedObj = flatted(obj, 'city_books');
console.log(JSON.stringify(flattenedObj, 0, 4));
This will output the following JSON:
{
"city_books": [
{
"name": "How to flatten objects like a pro",
"author": {
"first": "Anthony",
"second": "Mugendi"
}
},
{
"name": "How to flatten objects like a pro",
"author": {
"first": "Anthony",
"second": "Mugendi"
}
}
],
"obj": "CIRCULAR <obj>"
}
Also the rootKey allows you to use dot notation to determine how the final structure of the object looks like.
Consider the following:
flattenedObj = flatted(obj, 'city.books');
console.log(JSON.stringify(flattenedObj, 0, 4));
Which outputs:
{
"city": {
"books": [
{
"name": "How to flatten objects like a pro",
"author": {
"first": "Anthony",
"second": "Mugendi"
}
},
{
"name": "How to flatten objects like a pro",
"author": {
"first": "Anthony",
"second": "Mugendi"
}
}
]
},
"obj": "CIRCULAR <obj>"
}
Enjoy!