Skip to content

Commit

Permalink
Merge pull request #26 from petermorlion/array-support
Browse files Browse the repository at this point in the history
Add support for arrays
  • Loading branch information
jonschlinkert committed Apr 28, 2021
2 parents fb3e52d + 0dc7ff3 commit a68f550
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
16 changes: 12 additions & 4 deletions index.js
Expand Up @@ -37,15 +37,23 @@ function set(target, path, value, options) {
for (let i = 0; i < len; i++) {
let prop = keys[i];

if (i === len - 1) {
result(target, prop, value, merge);
break;
if (i < len - 1 && !isNaN(keys[i + 1]) && !target[prop]) {
target[prop] = [];
}

if (!isNaN(prop)) {
target.push({});
}

if (!isObject(target[prop])) {
target[prop] = {};
}

if (i === len - 1) {
result(target, prop, value, merge);
break;
}

target = target[prop];
}

Expand Down Expand Up @@ -107,4 +115,4 @@ function isObject(val) {
}

set.memo = {};
module.exports = set;
module.exports = set;
11 changes: 11 additions & 0 deletions test.js
Expand Up @@ -81,6 +81,17 @@ describe('set', function() {
assert.deepEqual(o.a[2].c, {y: 'z'});
});

it('should create an array if it does not already exist', function() {
var o = {};
set(o, 'a.0.a', {y: 'z'});
set(o, 'a.1.b', {y: 'z'});
set(o, 'a.2.c', {y: 'z'});
assert(Array.isArray(o.a));
assert.deepEqual(o.a[0].a, {y: 'z'});
assert.deepEqual(o.a[1].b, {y: 'z'});
assert.deepEqual(o.a[2].c, {y: 'z'});
});

it('should create a deeply nested property if it does not already exist', function() {
var o = {};
set(o, 'a.b.c.d.e', 'c');
Expand Down

0 comments on commit a68f550

Please sign in to comment.