I’ve got an object in a shape like this:
const objectExample = {
id: 2132131,
title: 'Some title',
tags: [],
isFree: true,
}
What I want to achieve is removing properties with an empty array (in this case tags). I’ve firstly tried
_.omitBy(objectExample, _.isEmpty)
but according to Lodash documentation isEmpty return true also for integers and booleans, so my id and isFree are also filtered out, which is not a desired behaviour.
I’ve tried to mix it up with _.isArray, but it still returns the same:
_.omitBy(transformedSession, _.isArray && _.isEmpty)
It seems like only takes into account the first condition. Can I mix them somehow?
Is there a simple, lodash way to remove properties when an array is empty, but leave integers and booleans? Wrapping integers with String() would be enough for me, but there are also booleans and I’m stuck.
Thanks in advance!
>Solution :
When you use _.omitBy(transformedSession, _.isArray && _.isEmpty) the expression _.isArray && _.isEmpty is evaluated to _.isEmpty since _.isArray is a function (a truthy value). So it’s identical to just writing _.omitBy(objectExample, _.isEmpty).
Use an arrow function and test if the value is an empty array:
const { omitBy, isArray, isEmpty } = _
const objectExample = {
id: 2132131,
title: 'Some title',
tags: [],
isFree: true,
}
const result = omitBy(objectExample,
v => isArray(v) && isEmpty(v)
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>