Skip to content

Commit

Permalink
add cleanKeys option
Browse files Browse the repository at this point in the history
  • Loading branch information
Matteo Dellea authored and nunofgs committed Dec 4, 2019
1 parent b9d3f4f commit 5efa2e2
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ $ npm install clean-deep --save

Option | Default value | Description
----------------- | ------------- | -----------------------------------
_cleanKeys_ | _[]_ | Remove specific keys, ie: `['foo', 'bar', ' ']`
_cleanValues_ | _[]_ | Remove specific values, ie: `['foo', 'bar', ' ']`
_emptyArrays_ | _true_ | Remove empty arrays, ie: `[]`
_emptyObjects_ | _true_ | Remove empty objects, ie: `{}`
Expand Down
8 changes: 7 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const transform = require('lodash.transform');
*/

module.exports = function cleanDeep(object, {
cleanKeys = [],
cleanValues = [],
emptyArrays = true,
emptyObjects = true,
Expand All @@ -20,9 +21,14 @@ module.exports = function cleanDeep(object, {
undefinedValues = true
} = {}) {
return transform(object, (result, value, key) => {
// Exclude specific keys.
if (cleanKeys.includes(key)) {
return;
}

// Recurse into arrays and objects.
if (Array.isArray(value) || isPlainObject(value)) {
value = cleanDeep(value, { cleanValues, emptyArrays, emptyObjects, emptyStrings, nullValues, undefinedValues });
value = cleanDeep(value, { cleanKeys, cleanValues, emptyArrays, emptyObjects, emptyStrings, nullValues, undefinedValues });
}

// Exclude specific values.
Expand Down
26 changes: 26 additions & 0 deletions test/src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,30 @@ describe('cleanDeep()', () => {
}
});
});

it('should remove specified keys if `cleanKeys` is passed', () => {
const object = {
foo: {
alsoMe: {
biz: 123,
},
bar: undefined,
biz: 123,
qux: [
undefined,
{},
true
],
removeMe: true,
},
removeMe: true,
};

expect(cleanDeep(object, { cleanKeys: ['removeMe', 'alsoMe'] })).toEqual({
foo: {
biz: 123,
qux: [true]
}
});
});
});

0 comments on commit 5efa2e2

Please sign in to comment.