Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lodash _.omitBy and _.isEmpty – removing an empty array, but leaving booleans and integers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading