Skip to content

Instantly share code, notes, and snippets.

@simonrenoult
Last active February 23, 2024 08:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonrenoult/2fa79fec8f035b2d35cef0767363b227 to your computer and use it in GitHub Desktop.
Save simonrenoult/2fa79fec8f035b2d35cef0767363b227 to your computer and use it in GitHub Desktop.
Recursive trim of objects and arrays using lodash
function sanitize(object) {
if (_.isString(object)) return _sanitizeString(object);
if (_.isArray(object)) return _sanitizeArray(object);
if (_.isPlainObject(object)) return _sanitizeObject(object);
return object;
}
function _sanitizeString(string) {
return _.isEmpty(string) ? null : string;
}
function _sanitizeArray(array) {
return _.filter(_.map(array, sanitize), _isProvided);
}
function _sanitizeObject(object) {
return _.pickBy(_.mapValues(object, sanitize), _isProvided);
}
function _isProvided(value) {
const typeIsNotSupported =
!_.isNull(value) &&
!_.isString(value) &&
!_.isArray(value) &&
!_.isPlainObject(value);
return typeIsNotSupported || !_.isEmpty(value);
}
describe(".sanitize(:obj)", () => {
[
{
title: "an empty string",
actual: "",
expected: null
},
{
title: "a list with empty strings",
actual: ["", "Something", ""],
expected: ["Something"]
},
{
title: "a list of empty strings",
actual: ["", "", ""],
expected: []
},
{
title: "a nested string list",
actual: { foo: ["", "Something", ""] },
expected: { foo: ["Something"] }
},
{
title: "a nested empty string",
actual: { foo: "" },
expected: {}
},
{
title: "two nested empty strings",
actual: { foo: { bar: "" }, qux: { pix: "" } },
expected: {}
},
{
title: "a nested empty string and something else",
actual: { foo: { bar: "" }, qux: "Something" },
expected: { qux: "Something" }
},
{
title: "a nested empty string in a list",
actual: { foo: [{ bar: "" }, "Something"] },
expected: { foo: ["Something"] }
},
{
title: "a nested empty array",
actual: { foo: [[], "Something"] },
expected: { foo: ["Something"] }
},
{
title: "a nested empty string in an empty array",
actual: { foo: [["", ""], "Something"] },
expected: { foo: ["Something"] }
},
{
title: "a nested empty string in a nested list",
actual: { foo: [[{ bar: "" }], "Something"] },
expected: { foo: ["Something"] }
},
{
title: "a nested object with empty string",
actual: { foo: { bar: true, qux: "" } },
expected: { foo: { bar: true } }
}
].forEach(({ title, actual, expected }) => {
describe(`When data is ${title}`, () => {
it("nullifies empty strings", () => {
const result = factory.sanitize(actual);
expect(result).toEqual(expected);
});
});
});
});
@JustAyush
Copy link

Thanks :)

@gordonk
Copy link

gordonk commented Feb 23, 2024

Thanks very helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment