diff --git a/index.js b/index.js index 2a5d7ca..803766c 100644 --- a/index.js +++ b/index.js @@ -54,9 +54,14 @@ function flatten (target, opts) { function unflatten (target, opts) { opts = opts || {} + if (opts.maxDepth === 0) { + return target + } + const delimiter = opts.delimiter || '.' const overwrite = opts.overwrite || false const transformKey = opts.transformKey || keyIdentity + const maxDepth = opts.maxDepth || Infinity const result = {} const isbuffer = isBuffer(target) @@ -80,7 +85,6 @@ function unflatten (target, opts) { function addKeys (keyPrefix, recipient, target) { return Object.keys(target).reduce(function (result, key) { result[keyPrefix + delimiter + key] = target[key] - return result }, recipient) } @@ -119,6 +123,7 @@ function unflatten (target, opts) { let key1 = getkey(split.shift()) let key2 = getkey(split[0]) let recipient = result + let depth = 1 while (key2 !== undefined) { if (key1 === '__proto__') { @@ -144,13 +149,18 @@ function unflatten (target, opts) { } recipient = recipient[key1] - if (split.length > 0) { + if (split.length > 0 && depth < maxDepth) { key1 = getkey(split.shift()) key2 = getkey(split[0]) + } else { + key1 = getkey(split.join(delimiter)) + key2 = undefined } + depth += 1 } // unflatten again for 'messy objects' + opts.maxDepth -= depth recipient[key1] = unflatten(target[key], opts) }) diff --git a/test/test.js b/test/test.js index 7f4ee3d..35cd9e3 100644 --- a/test/test.js +++ b/test/test.js @@ -231,6 +231,51 @@ suite('Unflatten', function () { })) }) + test('Custom Depth', function () { + assert.deepEqual(unflatten({ + 'hello.brave': { + 'new.world.again': 'good morning' + }, + 'all.you.need.is.love': 'love is all you need' + }, + { + maxDepth: 3 + }), { + hello: { + brave: { + 'new': { + 'world.again': 'good morning' + } + } + }, + all: { + you: { + need: { + 'is.love': 'love is all you need' + } + } + } + }) + }) + + test('Zero Depth', function () { + assert.deepEqual({ + hello: { + world: { + again: 'good morning' + } + } + }, unflatten({ + hello: { + world: { + again: 'good morning' + } + } + }, { + maxDepth: 0 + })) + }) + test('Multiple Keys', function () { assert.deepStrictEqual({ hello: {