just
just copied to clipboard
just-omit only handles root level omissions
easily could change to use code like just-safe-set, then it will handle nested objects/arrays. Working from the just-safe-set code
Changes
- new function name/export name:
omit
and dropped thevalue
param -
obj[lastProp] = value
becomesdelete obj[lastProp]
- if used on array,
delete obj[lastProp]
puts in null, so check for array and handle withobj.splice(parseInt(lastProp), 1)
module.exports = omit;
/*
var obj = {a: 3, b: {c:5, d:7}, e:[1,2,3]};
omit(obj, 'a'); // {b: {c:5, d:7}, e:[1,2,3]};
omit(obj, 'b.c'); // {a:3, b: {d:7}, e:[1,2,3]};
omit(obj, 'e.1'); // {a: 3, b: {c:5, d:7}, e:[1,3]};
*/
function omit(obj, propsArg) {
var props, lastProp;
if (Array.isArray(propsArg)) {
props = propsArg.slice(0);
}
if (typeof propsArg == 'string') {
props = propsArg.split('.');
}
if (typeof propsArg == 'symbol') {
props = [propsArg];
}
if (!Array.isArray(props)) {
throw new Error('props arg must be an array, a string or a symbol');
}
lastProp = props.pop();
if (!lastProp) {
return false;
}
prototypeCheck(lastProp);
var thisProp;
while ((thisProp = props.shift())) {
prototypeCheck(thisProp);
if (typeof obj[thisProp] == 'undefined') {
obj[thisProp] = {};
}
obj = obj[thisProp];
if (!obj || typeof obj != 'object') {
return false;
}
}
if (Array.isArray(obj)) {
obj.splice(parseInt(lastProp), 1);
} else {
delete obj[lastProp];
}
return true;
}
function prototypeCheck(prop) {
// coercion is intentional to catch prop values like `['__proto__']`
if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') {
throw new Error('setting of prototype values not supported');
}
}
Thanks, this is nice. Feel free to put up a PR including new tests
I will take a stab at it. Will be my first PR. Should it be a new function renamed as "just-safe-omit" to match up with just-safe-[get/set]? As you know both safe functions dig deep in nesting. Seems like the other functions (like just-pick) are all aimed at root level object and array methods? Happy to leave it name just-omit if you think thats better.
A new function sounds good. How about just-deep-omit?
Awesome