Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
20 changes: 20 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,26 @@ 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 an array if the target is null', ()=>{
const o = { a: null }
set(o, 'a.0', 'baz')
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');
Expand Down