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 filter by object of object

How to filter items by type?

const items = {
        'someHash0': {
          type: 'foo',
          name: 'a'
        },
        'someHash1': {
          type: 'foo',
          name: 'b'
        },
        'someHash2': {
          type: 'foo',
          name: 'c'
        },
        'someHash3': {
          type: 'baz',
          name: 'd'
        },
      };

I want to filter by type=foo and get that result:

const items = {
        'someHash0': {
          type: 'foo',
          name: 'a'
        },
        'someHash1': {
          type: 'foo',
          name: 'b'
        },
        'someHash2': {
          type: 'foo',
          name: 'c'
        }
      };

I tryied with

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

 return _.mapValues(pairs, function (item) {
     return (item.type === 'foo') ?? item
})

but it returns true/false instead of the whole object

>Solution :

map in general is for editing iterated inputs, so it’s not what you need.

You can do like this:

let result = _.filter(items, x => x.type === 'foo')

If you need to keep the same keys you could do it like this :

let result = _.pickBy(items, x => x.type === 'foo')
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