Desquid
Desquid

Reputation: 131

How to filter array on any matching value using lodash?

So I have objects that I want to be able to search for any matches of values.

For example:

let arr = [
    {
        a: 'foo',
        b: 'bar'
    },
    {
        a: 'bar',
        b: 'baz'
    },
    {
        a: 'foo',
        b: 'baz'
    }
];

and I want to be able to filter the array to contain any object that has a property with the value 'foo'.

Is there a way to do this with lodash? Something like:

_.filter(arr, function(obj) {
    return obj.anyPropertiesMatch('bar');
});

Upvotes: 1

Views: 9530

Answers (4)

Ori Drori
Ori Drori

Reputation: 191946

You can use Array.filter() and check if the value exists, using Object.values() to get an array of values, and Array.includes() to check if they include val:

const val = 'foo';

const arr = [{"a":"foo","b":"bar"},{"a":"bar","b":"baz"},{"a":"foo","b":"baz"}];

const result = arr.filter((o) => Object.values(o).includes(val));

console.log(result);

Or the lodash's equivalent using _.includes():

const val = 'foo';

const arr = [{"a":"foo","b":"bar"},{"a":"bar","b":"baz"},{"a":"foo","b":"baz"}];

const result = _.filter(arr, (o) => _.includes(o, val));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 4

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

It is as simple as this:

_.filter(arr, o=>_.includes(o,'foo'));

you can use lodash array function to any object directly and it will consider each values against each elements.

Here is an working example for you:

let arr = [
    {
        a: 'foo',
        b: 'bar'
    },
    {
        a: 'bar',
        b: 'baz'
    },
    {
        a: 'foo',
        b: 'baz'
    }
];

let res = _.filter(arr, o=>_.includes(o,'foo'));
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Upvotes: 2

alexmac
alexmac

Reputation: 19587

In lodash, you can use some method to validate that object has the field with the provided value:

let arr = [
  { a: 'foo', b: 'bar' },
  { a: 'bar', b: 'baz' },
  { a: 'foo', b: 'baz' }
];

let result = _.filter(arr, obj => _.some(obj, val => val === 'foo'));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

adeneo
adeneo

Reputation: 318182

Using LoDash _.filter to filter the array based on object values, gotten with _.values and checked with _.includes

let arr = [
    {
        a: 'foo',
        b: 'bar'
    },
    {
        a: 'bar',
        b: 'baz'
    },
    {
        a: 'foo',
        b: 'baz'
    }
];

let res = _.filter(arr, o => _.includes(_.values(o), 'foo'));

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Upvotes: 0

Related Questions