Skip to content

Instantly share code, notes, and snippets.

@simonrenoult
Last active Aug 6, 2022
Embed
What would you like to do?
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);
});
});
});
});
@minolettin
Copy link

minolettin commented Jun 5, 2020

thanks very useful :)

@JustAyush
Copy link

JustAyush commented May 19, 2022

Thanks :)

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