diff --git a/README.md b/README.md index 3295f75..6185ef3 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,7 @@ Use a custom delimiter for (un)flattening your objects, instead of `.`. ### safe -When enabled, both `flat` and `unflatten` will preserve arrays and their -contents. This is disabled by default. +When enabled `flatten` will preserve arrays and their contents. This is disabled by default. ``` javascript var flatten = require('flat') diff --git a/index.js b/index.js index ca8904a..40b1d62 100644 --- a/index.js +++ b/index.js @@ -49,7 +49,11 @@ function unflatten (target, opts) { var result = {} var isbuffer = isBuffer(target) - if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') { + if (Array.isArray(target)) { + return target.map(function (item) { + return unflatten(item, opts) + }) + } else if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') { return target } diff --git a/test/test.js b/test/test.js index 541c9d7..62b4a27 100644 --- a/test/test.js +++ b/test/test.js @@ -180,6 +180,46 @@ suite('Flatten', function () { 'hello.0500': 'darkness my old friend' }) }) + + suite('.safe', function () { + test('Should not protect arrays when false', function () { + assert.deepEqual(flatten({ + hello: [ + { world: { again: 'foo' } }, + { lorem: 'ipsum' } + ] + }, { + safe: false + }), { + 'hello.0.world.again': 'foo', + 'hello.1.lorem': 'ipsum' + }) + }) + + test('Should protect arrays when true', function () { + assert.deepEqual(flatten({ + hello: [ + { world: { again: 'foo' } }, + { lorem: 'ipsum' } + ], + another: { + nested: [{ array: { too: 'deep' } }] + }, + lorem: { + ipsum: 'whoop' + } + }, { + safe: true + }), { + hello: [ + { world: { again: 'foo' } }, + { lorem: 'ipsum' } + ], + 'lorem.ipsum': 'whoop', + 'another.nested': [{ array: { too: 'deep' } }] + }) + }) + }) }) suite('Unflatten', function () { @@ -327,41 +367,17 @@ suite('Unflatten', function () { }) suite('.safe', function () { - test('Should protect arrays when true', function () { - assert.deepEqual(flatten({ - hello: [ - { world: { again: 'foo' } }, - { lorem: 'ipsum' } - ], - another: { - nested: [{ array: { too: 'deep' } }] - }, - lorem: { - ipsum: 'whoop' - } - }, { - safe: true - }), { - hello: [ - { world: { again: 'foo' } }, - { lorem: 'ipsum' } - ], - 'lorem.ipsum': 'whoop', - 'another.nested': [{ array: { too: 'deep' } }] - }) - }) - - test('Should not protect arrays when false', function () { - assert.deepEqual(flatten({ + test('Should unflatten dot notation keys nested in array', function () { + assert.deepEqual(unflatten({ hello: [ - { world: { again: 'foo' } }, - { lorem: 'ipsum' } + { 'something.nested': true } ] }, { safe: false }), { - 'hello.0.world.again': 'foo', - 'hello.1.lorem': 'ipsum' + hello: [ + { something: { nested: true } } + ] }) }) })