diff --git a/index.js b/index.js index 42e1ddc..d86a68f 100644 --- a/index.js +++ b/index.js @@ -63,6 +63,10 @@ export function unflatten (target, opts) { // safely ensure that the key is // an integer. function getkey (key) { + // `Number('')` is 0 (not NaN), so an empty-string key would be coerced to + // the numeric index 0 and renamed; keep it as-is. + if (key === '') return key + const parsedKey = Number(key) return ( diff --git a/test/test.js b/test/test.js index ef01c9b..6c74eaf 100644 --- a/test/test.js +++ b/test/test.js @@ -566,6 +566,12 @@ describe('Arrays', function () { })) }) + test('Should keep an empty-string key instead of renaming it to 0', function () { + assert.deepStrictEqual({ '': 1, x: 2 }, unflatten({ '': 1, x: 2 })) + assert.deepStrictEqual({ a: { '': 1 } }, unflatten({ 'a.': 1 })) + assert.deepStrictEqual({ '': 1, x: 2 }, unflatten(flatten({ '': 1, x: 2 }))) + }) + test('Array typed objects should be restored by unflatten', function () { assert.strictEqual( Object.prototype.toString.call(['foo', 'bar'])