Sometimes, we want to filter an array of objects that contains a string using Lodash and JavaScript.
In this article, we’ll look at how to filter an array of objects that contains a string using Lodash and JavaScript.
How to filter an array of objects that contains a string using Lodash and JavaScript?
To filter an array of objects that contains a string using Lodash and JavaScript, we can use the string includes
method.
For instance, we write:
const collection = [{
val: "CPP@4@1900-01-01"
},
{
val: "CMIP@5@1900-01-01"
},
{
val: "CMIP@6@1900-01-01"
},
{
val: "CMIP@7@1900-01-01"
},
{
val: "CPP@8@1900-01-01"
},
{
val: "CMIP@9@1900-01-01"
},
{
val: "CMIP@10@1900-01-01"
}
];
const search = 'CPP@';
const results = _.filter(collection, (item) => {
return item.val.includes(search);
});
console.log(results);
to call filter
with the collection
to filter and a callback that returns the condition of the items we want to return.
We use includes
to check if item.val
has search
inside.
Therefore, results
is:
[
{
"val": "CPP@4@1900-01-01"
},
{
"val": "CPP@8@1900-01-01"
}
]
Conclusion
To filter an array of objects that contains a string using Lodash and JavaScript, we can use the string includes
method.