Skip to content

Commit

Permalink
Add support for snake casing in flatten method
Browse files Browse the repository at this point in the history
  • Loading branch information
theoschao committed Aug 22, 2017
1 parent b6633d0 commit cb87c1a
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# flat [![Build Status](https://secure.travis-ci.org/hughsk/flat.png?branch=master)](http://travis-ci.org/hughsk/flat)

This is a fork of hughsk/flat that adds an option to snakify all json keys (including nested) before flattening

Take a nested Javascript object and flatten it, or unflatten an object with
delimited keys.

Expand Down Expand Up @@ -62,6 +64,10 @@ unflatten({

## Options

### snakify

When enabled for `flatten`, each key (nested & unstead) will be formatted using snake_case before flattening.

### delimiter

Use a custom delimiter for (un)flattening your objects, instead of `.`.
Expand Down
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var isBuffer = require('is-buffer')
var snake = require('to-snake-case')

module.exports = flatten
flatten.flatten = flatten
Expand All @@ -9,11 +10,13 @@ function flatten (target, opts) {

var delimiter = opts.delimiter || '.'
var maxDepth = opts.maxDepth
var snakify = opts.snakify || false
var output = {}

function step (object, prev, currentDepth) {
currentDepth = currentDepth || 1
Object.keys(object).forEach(function (key) {
var thisKey = snakify ? snake(key) : key
var value = object[key]
var isarray = opts.safe && Array.isArray(value)
var type = Object.prototype.toString.call(value)
Expand All @@ -24,8 +27,8 @@ function flatten (target, opts) {
)

var newKey = prev
? prev + delimiter + key
: key
? prev + delimiter + thisKey
: thisKey

if (!isarray && !isbuffer && isobject && Object.keys(value).length &&
(!opts.maxDepth || currentDepth < maxDepth)) {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"test": "test"
},
"dependencies": {
"is-buffer": "~1.1.5"
"is-buffer": "~1.1.5",
"to-snake-case": "^1.0.0"
},
"repository": {
"type": "git",
Expand Down
10 changes: 10 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ suite('Unflatten Primitives', function () {
})

suite('Flatten', function () {
test('Snakify keys before flattening', function () {
assert.deepEqual(flatten({
hello: {
worldFooBar: 'good morning'
}
}, {snakify: true}), {
'hello.world_foo_bar': 'good morning'
})
})

test('Nested once', function () {
assert.deepEqual(flatten({
hello: {
Expand Down

0 comments on commit cb87c1a

Please sign in to comment.