From 82be35dbd7e10a294220676636af201d6a5443d5 Mon Sep 17 00:00:00 2001 From: Nuno Sousa Date: Tue, 15 Oct 2019 22:16:06 +0100 Subject: [PATCH] Add custom values support --- README.md | 1 + src/index.js | 8 +++++++- test/src/index.test.js | 17 +++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f80b77d..07e9210 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ $ npm install clean-deep --save Option | Default value | Description ----------------- | ------------- | ----------------------------------- +_cleanValues_ | _[]_ | Remove specific values, ie: `['foo', 'bar', ' ']` _emptyArrays_ | _true_ | Remove empty arrays, ie: `[]` _emptyObjects_ | _true_ | Remove empty objects, ie: `{}` _emptyStrings_ | _true_ | Remove empty strings, ie: `''` diff --git a/src/index.js b/src/index.js index 5313dd6..2b62e04 100755 --- a/src/index.js +++ b/src/index.js @@ -12,6 +12,7 @@ const transform = require('lodash.transform'); */ module.exports = function cleanDeep(object, { + cleanValues = [], emptyArrays = true, emptyObjects = true, emptyStrings = true, @@ -21,7 +22,12 @@ module.exports = function cleanDeep(object, { return transform(object, (result, value, key) => { // Recurse into arrays and objects. if (Array.isArray(value) || isPlainObject(value)) { - value = cleanDeep(value, { emptyArrays, emptyObjects, emptyStrings, nullValues, undefinedValues }); + value = cleanDeep(value, { cleanValues, emptyArrays, emptyObjects, emptyStrings, nullValues, undefinedValues }); + } + + // Exclude specific values. + if (cleanValues.includes(value)) { + return; } // Exclude empty objects. diff --git a/test/src/index.test.js b/test/src/index.test.js index bc633e5..b167976 100755 --- a/test/src/index.test.js +++ b/test/src/index.test.js @@ -64,6 +64,23 @@ describe('cleanDeep()', () => { }); }); + it('should support custom values', () => { + const object = { + biz: { + baz: 123 + }, + foo: { + bar: 'abc' + } + }; + + expect(cleanDeep(object, { cleanValues: ['abc'] })).toEqual({ + biz: { + baz: 123 + } + }); + }); + it('should include empty objects if `emptyObjects` is `false`', () => { const object = { biz: {