diff --git a/README.md b/README.md index 2e4cb3c..9789222 100644 --- a/README.md +++ b/README.md @@ -158,3 +158,30 @@ flatten({ // 'key3.a': { b: { c: 2 } } // } ``` + +### uniformFlatten + +If maxDepth is set, will flatten each object in the collection to the depth specified by maxDepth. This uniformly flattens the object at the depth specified. + +This is usually set in combination with the maxDepth option. + +``` javascript +var flatten = require('flat') + +flatten({ + key1: { + keyA: {a: 'valueI'} + }, + key2: { + keyB: {a: {b: 'valueII'}} + }, + key3: { a: { b: { c: 2 } } } +}, { maxDepth: 2, uniformFlatten: true}) + + +//{ +// 'key1.keyA.a': 'valueI', +// 'key2.keyB.a': { b: 'valueII' }, +// 'key3.a.b': { c: 2 } +//} +``` diff --git a/index.js b/index.js index 4d6914a..d040575 100644 --- a/index.js +++ b/index.js @@ -7,11 +7,11 @@ function flatten(target, opts) { var delimiter = opts.delimiter || '.' var maxDepth = opts.maxDepth - var currentDepth = 1 - var output = {} - - function step(object, prev) { - Object.keys(object).forEach(function(key) { + var output = {}; + var numberToFlatten = 1; + function step(object, prev, currentDepth) { + currentDepth = currentDepth || 1; + Object.keys(object).forEach(function(key) { var value = object[key] var isarray = opts.safe && Array.isArray(value) var type = Object.prototype.toString.call(value) @@ -26,19 +26,20 @@ function flatten(target, opts) { : key if (!opts.maxDepth) { - maxDepth = currentDepth + 1; + maxDepth = numberToFlatten + 1; } - if (!isarray && !isbuffer && isobject && Object.keys(value).length && currentDepth < maxDepth) { - ++currentDepth - return step(value, newKey) + var flattenCondition = (opts.uniformFlatten) ? currentDepth : numberToFlatten + if (!isarray && !isbuffer && isobject && Object.keys(value).length && flattenCondition < maxDepth) { + ++numberToFlatten; + return step(value, newKey, currentDepth + 1) } - + output[newKey] = value }) } - step(target) + step(target); return output } diff --git a/test/test.js b/test/test.js index 707901b..25e4f25 100644 --- a/test/test.js +++ b/test/test.js @@ -154,7 +154,29 @@ suite('Flatten', function() { } }) }) -}) + + test('Uniform Flatten with Depth', function(){ + assert.deepEqual(flatten({ + hello: { + world: {again: 'good morning'} + }, + salut: { + monde: {encore: {bonne: 'matin'}} + }, + konnichiwa: { sekai: { mou: { ohayou: 'gozaimasu' } } } + }, { + maxDepth: 3, + uniformFlatten: true + }), + { + 'hello.world.again': 'good morning', + 'salut.monde.encore': { bonne: 'matin' }, + 'konnichiwa.sekai.mou': { ohayou: 'gozaimasu' } + }); + }) +}); + + suite('Unflatten', function() { test('Nested once', function() {