File tree Expand file tree Collapse file tree 2 files changed +26
-3
lines changed Expand file tree Collapse file tree 2 files changed +26
-3
lines changed Original file line number Diff line number Diff line change 82
82
83
83
// Create namespace (object) where none exists.
84
84
// 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 ) ) {
86
89
current [ piece ] = { } ;
87
90
}
88
91
91
94
current [ piece ] = value ;
92
95
} else {
93
96
// We do not overwrite existing path pieces by default
94
- if ( typeof current [ piece ] !== 'object' ) {
97
+ if ( typeof current [ piece ] !== 'object' || current [ piece ] === null ) {
95
98
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.)' ) ;
96
99
}
97
100
Original file line number Diff line number Diff line change @@ -28,12 +28,32 @@ describe("dottie.set", function () {
28
28
expect ( data . values . level1 ) . to . equal ( 'foo' ) ;
29
29
} ) ;
30
30
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
+
31
51
it ( 'should be able to set with an array path' , function ( ) {
32
52
dottie . set ( data , [ 'some.dot.containing' , 'value' ] , 'razzamataz' ) ;
33
53
expect ( data [ 'some.dot.containing' ] . value ) . to . equal ( 'razzamataz' ) ;
34
54
} ) ;
35
55
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 ( ) {
37
57
expect ( function ( ) {
38
58
dottie . set ( data , 'foo.bar.baz' , 'someValue' ) ;
39
59
} ) . to . throw ( ) ;
You can’t perform that action at this time.
0 commit comments