Skip to content

Commit

Permalink
Setting a null value should convert it to object (#37)
Browse files Browse the repository at this point in the history
* Setting a null value should convert it to object (like it works for undefined values)

* Overwrite null values only if force is true
  • Loading branch information
slavivanov committed Feb 7, 2023
1 parent b581120 commit dbf26a6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
7 changes: 5 additions & 2 deletions dottie.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@

// Create namespace (object) where none exists.
// If `force === true`, bruteforce the path without throwing errors.
if (!hasOwnProp.call(current, piece) || current[piece] === undefined || (typeof current[piece] !== 'object' && options && options.force === true)) {
if (
!hasOwnProp.call(current, piece)
|| current[piece] === undefined
|| ((typeof current[piece] !== 'object' || current[piece] === null) && options && options.force === true)) {
current[piece] = {};
}

Expand All @@ -91,7 +94,7 @@
current[piece] = value;
} else {
// We do not overwrite existing path pieces by default
if (typeof current[piece] !== 'object') {
if (typeof current[piece] !== 'object' || current[piece] === null) {
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.)');
}

Expand Down
22 changes: 21 additions & 1 deletion test/set.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,32 @@ describe("dottie.set", function () {
expect(data.values.level1).to.equal('foo');
});

it("should throw when overwriting a nested null value with force: false", function () {
var data = {
'values': null
};


expect(function () {
dottie.set(data, 'values.level1', 'foo');
}).to.throw();
});

it("should handle setting a nested value on an null value (should convert null to object) with force: true", function () {
var data = {
'values': null
};

dottie.set(data, 'values.level1', 'foo', { force: true });
expect(data.values.level1).to.equal('foo');
});

it('should be able to set with an array path', function () {
dottie.set(data, ['some.dot.containing', 'value'], 'razzamataz');
expect(data['some.dot.containing'].value).to.equal('razzamataz');
});

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

0 comments on commit dbf26a6

Please sign in to comment.