lodash-omitdeep
Version:
lodash omitDeep/omitByDeep object key/value recursively
61 lines (60 loc) • 2.18 kB
JavaScript
import lodash from "lodash";
//#region src/omitDeep/omitDeep.ts
const needOmit = (value) => !lodash.isNil(value) && (lodash.isPlainObject(value) || Array.isArray(value));
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable properties of `object` that are not omitted.
*
* @category Function
* @param object The source object.
* @param [paths] The property names to omit, specified
* individually or in arrays.
* @returns Returns the new object.
* @example
*
* const object = { 'a': 1, 'b': 2, 'c': { 'a': 1, 'b': 2 } };
*
* omitDeep(object, ['b', 'a']);
* // => { 'c': {} }
*/
const omitDeep = (object, ...paths) => {
function omitDeepOnOwnProps(object) {
if (!Array.isArray(object) && !lodash.isPlainObject(object)) return object;
if (Array.isArray(object)) return object.map((element) => needOmit(element) ? omitDeep(element, ...paths) : element);
const temp = {};
for (const [key, value] of Object.entries(object)) temp[key] = needOmit(value) ? omitDeep(value, ...paths) : value;
return lodash.omit(temp, ...paths);
}
return omitDeepOnOwnProps(object);
};
//#endregion
//#region src/omitDeepBy/omitDeepBy.ts
/**
* The opposite of `_.pickBy`; this method creates an object composed of the
* own and inherited enumerable properties of `object` that `predicate`
* doesn't return truthy for.
*
* @category Function
* @param object The source object.
* @param [predicate] The function invoked per property.
* @returns Returns the new object.
* @example
*
* const object = { 'a': 1, 'b': null, 'c': { 'a': 1, 'b': null } };
*
* omitByDeep(object, _.isNil);
* // => { 'a': 1, 'c': { 'a': 1 } }
*/
const omitDeepBy = (object, cb) => {
function omitByDeepByOnOwnProps(object) {
if (!Array.isArray(object) && !lodash.isPlainObject(object)) return object;
if (Array.isArray(object)) return object.map((element) => omitDeepBy(element, cb));
const temp = {};
for (const [key, value] of Object.entries(object)) temp[key] = omitDeepBy(value, cb);
return lodash.omitBy(temp, cb);
}
return omitByDeepByOnOwnProps(object);
};
//#endregion
export { omitDeep, omitDeepBy };
//# sourceMappingURL=index.mjs.map