这是一个独立的函数,取决于我编写的 lodash/下划线,它的作用相同。
它为对象或数组中的每个 (value, indexOrKey) 对调用回调,如果为 true,将在结果对象中忽略该对。
在访问值后调用回调,因此您可以省略与您的条件匹配的整个值子树。
function deepOmit(sourceObj, callback, thisArg) {
var destObj, i, shouldOmit, newValue;
if (_.isUndefined(sourceObj)) {
return undefined;
}
callback = thisArg ? _.bind(callback, thisArg) : callback;
if (_.isPlainObject(sourceObj)) {
destObj = {};
_.forOwn(sourceObj, function(value, key) {
newValue = deepOmit(value, callback);
shouldOmit = callback(newValue, key);
if (!shouldOmit) {
destObj[key] = newValue;
}
});
} else if (_.isArray(sourceObj)) {
destObj = [];
for (i = 0; i <sourceObj.length; i++) {
newValue = deepOmit(sourceObj[i], callback);
shouldOmit = callback(newValue, i);
if (!shouldOmit) {
destObj.push(newValue);
}
}
} else {
return sourceObj;
}
return destObj;
}
一些样品
var sourceObj = {
a1: [ undefined, {}, { o: undefined } ],
a2: [ 1, undefined ],
o: { s: 's' }
};
deepOmit(sourceObj, function (value) {
return value === undefined;
});
//=> { a1: [ {}, {} ], a2: [ 1 ], o: { s: 's' }}
//omit empty objects and arrays too
deepOmit(sourceObj, function (value) {
return value === undefined ||
(_.isPlainObject(value) && !_.keys(value).length) ||
(_.isArray(value) && !value.length);
});
//=> { a2: [ 1 ], o: { s: 's' }}
//indexOrKey is the string key or the numeric index if the object is array
deepOmit([ 0, 1, 2, 3, 4 ], function (value, indexOrKey) {
return indexOrKey % 2;
});
//=> [ 0, 2, 4 ]