https://github.com/jessie-codes/safe-flat
Safely flatten a nested JavaScript object.
https://github.com/jessie-codes/safe-flat
flat javascript nodejs
Last synced: 12 months ago
JSON representation
Safely flatten a nested JavaScript object.
- Host: GitHub
- URL: https://github.com/jessie-codes/safe-flat
- Owner: jessie-codes
- License: mit
- Created: 2019-04-21T21:09:41.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2024-09-19T05:42:36.000Z (over 1 year ago)
- Last Synced: 2025-04-17T22:42:16.233Z (about 1 year ago)
- Topics: flat, javascript, nodejs
- Language: JavaScript
- Homepage:
- Size: 447 KB
- Stars: 5
- Watchers: 1
- Forks: 8
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# safe-flat
> Safely flatten a nested JavaScript object.
[](https://nodei.co/npm/safe-flat/)
[](http://commitizen.github.io/cz-cli/)
[](http://standardjs.com)
[](https://coveralls.io/github/jessie-codes/safe-flat?branch=master)
[](https://snyk.io/test/github/jessie-codes/safe-flat)
## Installation
``` bash
$ npm i safe-flat
```
## Methods
### flatten(obj, [delimiter])
Flattens an object to one level deep. Optionally takes a custom `delimiter`, otherwise uses `.` by default. Circular references within the object will be replaced with `[Circular]`.
``` javascript
const { flatten } = require('safe-flat')
const original = {
a: {
b: {
c: [{
val: 'one'
}, {
val: 'two'
}],
d: 'three'
},
e: 'four',
}
}
original.a.b.f = original.a.b
original.a.b.c.push(original.a)
const flat = flatten(original)
/*
{
'a.b.c.0.val': 'one',
'a.b.c.1.val': 'two',
'a.b.c.2': '[Circular]',
'a.b.d': 'three',
'a.e': 'four',
'a.b.f': '[Circular]'
}
*/
const underscoreFlat = flatten(original, '_')
/*
{
'a_b_c_0_val': 'one',
'a_b_c_1_val': 'two',
'a_b_c_2': '[Circular]',
'a_b_d': 'three',
'a_e': 'four',
'a_b_f': '[Circular]'
}
*/
```
### unflatten(obj, [delimiter])
Unflattens an object back to its original nested form. Optionally takes a custom `delimiter`, otherwise uses `.` by default. Circular references denoted by `[Circular]` are treated as Strings.
``` javascript
const { unflatten } = require('safe-flat')
const original = {
'a.b.c.0.val': 'one',
'a.b.c.1.val': 'two',
'a.b.c.2': '[Circular]',
'a.b.d': 'three',
'a.e': 'four',
'a.b.f': '[Circular]'
}
const unflat = unflatten(original)
/*{
a:{
b:{
c:[
{
val:'one'
},
{
val:'two'
},
'[Circular]'
],
d:'three',
f:'[Circular]'
},
e:'four'
}
}*/
```