diff --git a/README.md b/README.md index 2e4cb3c..0486fe9 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 `.`. diff --git a/index.js b/index.js index ca8904a..e1ece0b 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,5 @@ var isBuffer = require('is-buffer') +var snake = require('to-snake-case') module.exports = flatten flatten.flatten = flatten @@ -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) @@ -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)) { diff --git a/package.json b/package.json index ca75202..5c80b6f 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/test/test.js b/test/test.js index 541c9d7..4809a84 100644 --- a/test/test.js +++ b/test/test.js @@ -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: {