Skip to content

Commit dbf26a6

Browse files
authored
Setting a null value should convert it to object (#37)
* Setting a null value should convert it to object (like it works for undefined values) * Overwrite null values only if force is true
1 parent b581120 commit dbf26a6

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

dottie.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@
8282

8383
// Create namespace (object) where none exists.
8484
// If `force === true`, bruteforce the path without throwing errors.
85-
if (!hasOwnProp.call(current, piece) || current[piece] === undefined || (typeof current[piece] !== 'object' && options && options.force === true)) {
85+
if (
86+
!hasOwnProp.call(current, piece)
87+
|| current[piece] === undefined
88+
|| ((typeof current[piece] !== 'object' || current[piece] === null) && options && options.force === true)) {
8689
current[piece] = {};
8790
}
8891

@@ -91,7 +94,7 @@
9194
current[piece] = value;
9295
} else {
9396
// We do not overwrite existing path pieces by default
94-
if (typeof current[piece] !== 'object') {
97+
if (typeof current[piece] !== 'object' || current[piece] === null) {
9598
throw new Error('Target key "' + piece + '" is not suitable for a nested value. (It is in use as non-object. Set `force` to `true` to override.)');
9699
}
97100

test/set.test.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,32 @@ describe("dottie.set", function () {
2828
expect(data.values.level1).to.equal('foo');
2929
});
3030

31+
it("should throw when overwriting a nested null value with force: false", function () {
32+
var data = {
33+
'values': null
34+
};
35+
36+
37+
expect(function () {
38+
dottie.set(data, 'values.level1', 'foo');
39+
}).to.throw();
40+
});
41+
42+
it("should handle setting a nested value on an null value (should convert null to object) with force: true", function () {
43+
var data = {
44+
'values': null
45+
};
46+
47+
dottie.set(data, 'values.level1', 'foo', { force: true });
48+
expect(data.values.level1).to.equal('foo');
49+
});
50+
3151
it('should be able to set with an array path', function () {
3252
dottie.set(data, ['some.dot.containing', 'value'], 'razzamataz');
3353
expect(data['some.dot.containing'].value).to.equal('razzamataz');
3454
});
3555

36-
it("should throw error when setting a nested value on an existing key with a non-object value", function() {
56+
it("should throw error when setting a nested value on an existing key with a non-object value", function () {
3757
expect(function () {
3858
dottie.set(data, 'foo.bar.baz', 'someValue');
3959
}).to.throw();

0 commit comments

Comments
 (0)