diff --git a/lib/index.js b/lib/index.js index e8870bd..46606fe 100644 --- a/lib/index.js +++ b/lib/index.js @@ -129,38 +129,35 @@ exports.has = function has(path, o) { * @param {Object} o */ -exports.unset = function unset(path, o) { +exports.unset = function(path, o) { if (o === null) return false; const parts = getPartsByPath(path), - len = parts.length, - last = len - 1; - let cur = o, - i = 0, - part = ''; + last = parts.length - 1; - for (i = 0; i < len; ++i) { - part = parts[i]; - if ( - ignoreProperties.has(part) || - typeof cur !== 'object' || - cur === null || - !(part in cur) - ) { - return false; - } + return _unsetNext(o, parts, 0, last); +}; - if (i === last) { - return delete cur[part]; - } - cur = cur instanceof Map - ? cur.get(part) - : cur[part]; +function _unsetNext(cur, parts, i, last) { + const part = parts[i]; + + if ( + ignoreProperties.has(part) || + !((typeof cur === 'object' && cur !== null && part in cur) || Array.isArray(cur)) || + cur === null + ) { + return false; } - return true; -}; + if (i === last) { + return delete cur[part]; + } else if (Array.isArray(cur[part])) { + return cur[parts[i]].reduce((acc, next) => acc && _unsetNext(next, parts, i + 1, last), true); + } else { + return _unsetNext(cur instanceof Map ? cur.get(part) : cur[part], parts, i + 1, last); + } +} /** * Sets the `val` at the given `path` of object `o`. diff --git a/test/index.js b/test/index.js index 47c4c73..00959b5 100644 --- a/test/index.js +++ b/test/index.js @@ -1903,6 +1903,10 @@ describe('mpath', function() { mpath.unset('a.b', o); assert.deepEqual(o, { a: {} }); + o = { a: [{ b: 1 }, { b: 2 }] }; + mpath.unset('a.b', o); + assert.deepEqual(o, { a: [{}, {}] }); + o = { a: null }; mpath.unset('a.b', o); assert.deepEqual(o, { a: null });