Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 21 additions & 24 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
4 changes: 4 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down