Skip to content

Commit

Permalink
Merge pull request #22 from zeidoo/master
Browse files Browse the repository at this point in the history
add support for array creation
  • Loading branch information
jonschlinkert committed Apr 28, 2021
2 parents 042bb56 + 6169f1b commit db9602f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ function set(target, path, value, options) {
let prop = keys[i];

if (!isObject(target[prop])) {
target[prop] = {};
let nextProp = i + 1 < len ? keys[i + 1] : "";
let shouldBeArray = !isNaN(+nextProp);
target[prop] = shouldBeArray ? [] : {};
}

if (i === len - 1) {
Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ describe('set', function() {
assert.equal(o.a.b, 'c');
});

it('should create a nested array if it does not already exist', function() {
const o = {};
set(o, 'a.0', 'c');
set(o, 'a.1', 'd');
assert(Array.isArray(o.a));
assert.equal(o.a[0], 'c');
let actual = "";
o.a.map(i=> actual +=i);
assert.equal(actual, "cd");
});

it('should merge an existing value with the given value', function() {
var o = {a: {b: {c: 'd'}}};
set(o, 'a.b', {y: 'z'}, { merge: true });
Expand Down

0 comments on commit db9602f

Please sign in to comment.