Skip to content

Commit

Permalink
fix: correct set to properly handle <0> keys in path
Browse files Browse the repository at this point in the history
+ verify handling of <''> keys, too
  • Loading branch information
nikku committed Mar 15, 2021
1 parent 9b9ba30 commit 682e3af
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/object.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { forEach } from './collection';

import { isObject, isUndefined } from './lang';
import {
isObject,
isUndefined,
isDefined
} from './lang';


/**
Expand Down Expand Up @@ -37,11 +41,11 @@ export function set(target, path, value) {
var nextKey = path[idx + 1];
var nextTarget = currentTarget[key];

if (nextKey && !nextTarget) {
if (isDefined(nextKey) && !nextTarget) {
nextTarget = currentTarget[key] = isNaN(+nextKey) ? {} : [];
}

if (!nextKey) {
if (isUndefined(nextKey)) {
if (isUndefined(value)) {
delete currentTarget[key];
} else {
Expand Down
26 changes: 26 additions & 0 deletions test/object.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,18 +305,40 @@ describe('object', function() {
expect(set({}, ['a'], true)).to.eql({
a: true
});

expect(set({}, [''], 'A')).to.eql({
'': 'A'
});

expect(set({}, [ 0 ], 'A')).to.eql({
'0': 'A'
});
});


it('should set array value', function() {

expect(set([0, 1, 2], [1], 'A')).to.eql([ 0, 'A', 2]);

expect(set([0, 1, 2], [1], 0)).to.eql([ 0, 0, 2]);

expect(set({
a: [0, 0]
}, [ 'a', 1 ], 1)).to.eql({
a: [ 0, 1 ]
});

expect(
set({
a: [
{ b: 'FOO' }
]
}, [ 'a', 0, 'b' ], 'BAR')
).to.eql({
a: [
{ b: 'BAR' }
]
});
});


Expand All @@ -336,6 +358,10 @@ describe('object', function() {
expect(set({
a: false
}, [ 'a' ], undefined)).to.eql({});

expect(set({
'': false
}, [ '' ], undefined)).to.eql({});
});


Expand Down

0 comments on commit 682e3af

Please # to comment.