From 56a44ed2834f1d06cc72e6582e1d1d94cfdabbed Mon Sep 17 00:00:00 2001 From: Robert Kempton Date: Fri, 25 Mar 2022 11:54:51 -0600 Subject: [PATCH 1/3] add test to illustrate issue with number properties --- test/test.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/test.js b/test/test.js index 92e200b..ffcbb95 100644 --- a/test/test.js +++ b/test/test.js @@ -123,6 +123,12 @@ describe('set-value', () => { assert.deepEqual(o.a[2].c, { y: 'z' }); }); + it('should not delete number properties from an object', ()=>{ + const o = {a: {0: 'foo', 1: 'bar'}} + set(o, 'a.0', 'baz') + assert.deepEqual(o, {a: {0: 'baz', 1: 'bar'}}) + }) + it('should create a deeply nested property if it does not already exist', () => { const o = {}; set(o, 'a.b.c.d.e', 'c'); From 2a24ab2b4e6c1d9377e8a57655a394041aa1c53c Mon Sep 17 00:00:00 2001 From: Robert Kempton Date: Fri, 25 Mar 2022 19:25:19 -0600 Subject: [PATCH 2/3] Check if the target is an object instead of an array to avoid deleting properties fixes #35 --- index.js | 2 +- test/test.js | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index ecf8371..4036a29 100644 --- a/index.js +++ b/index.js @@ -145,7 +145,7 @@ const setValue = (target, path, value, options) => { break; } - if (typeof next === 'number' && !Array.isArray(obj[key])) { + if (typeof next === 'number' && (typeof obj[key] !== 'object' || obj[key] === null)) { obj = obj[key] = []; continue; } diff --git a/test/test.js b/test/test.js index ffcbb95..c34394d 100644 --- a/test/test.js +++ b/test/test.js @@ -124,9 +124,15 @@ describe('set-value', () => { }); it('should not delete number properties from an object', ()=>{ - const o = {a: {0: 'foo', 1: 'bar'}} + const o = { a: { 0: 'foo', 1: 'bar' } } set(o, 'a.0', 'baz') - assert.deepEqual(o, {a: {0: 'baz', 1: 'bar'}}) + assert.deepEqual(o, { a: { 0: 'baz', 1: 'bar' } }) + }) + + it('should create an array if the target is null', ()=>{ + const o = { a: null } + set(o, 'a.0', 'baz') + assert.deepEqual(o, { a: ['baz'] }) }) it('should create a deeply nested property if it does not already exist', () => { From 555691877a95ced6df6fe4ed7778271bd804bad5 Mon Sep 17 00:00:00 2001 From: Robert Kempton Date: Fri, 25 Mar 2022 19:28:55 -0600 Subject: [PATCH 3/3] add test case for non object values --- test/test.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/test.js b/test/test.js index c34394d..d3ffdc7 100644 --- a/test/test.js +++ b/test/test.js @@ -135,6 +135,14 @@ describe('set-value', () => { assert.deepEqual(o, { a: ['baz'] }) }) + it('should create an array if the target is not an array or object', ()=>{ + const o = { a: false, b: undefined, c: 5 } + set(o, 'a.0', 'foo') + set(o, 'b.0', 'bar') + set(o, 'c.0', 'baz') + assert.deepEqual(o, { a: ['foo'], b: ['bar'], c: ['baz'] }) + }) + it('should create a deeply nested property if it does not already exist', () => { const o = {}; set(o, 'a.b.c.d.e', 'c');