Let's say I have an array of objects like this:
[{
away: "Seattle Seahawks",
home: "Kansas City Chiefs",
},
{
away: "Houston Texans",
home: "San Francisco 49ers",
},
{
away: "Dallas Cowboys",
home: "Los Angeles Rams",
}]
Requirements:
Search every object and for the keyword 49er
and have it return object #2.
Search every object for the keyword cow
and have it return object #3.
Search every object for the keyword an
and have it return all three objects.
What would be the best way to achieve this in lodash? Thanks!
My solution with _.flow
:
const my_arr = [{
away: "Seattle Seahawks",
home: "Kansas City Chiefs",
},
{
away: "Houston Texans",
home: "San Francisco 49ers",
},
{
away: "Dallas Cowboys",
home: "Los Angeles Rams",
}]
function flowFilter(array, substr) {
return _.filter(array, _.flow(
_.identity,
_.values,
_.join,
_.toLower,
_.partialRight(_.includes, substr)
));
}
const one = flowFilter(my_arr, '49er');
const two = flowFilter(my_arr, 'cow');
const three = flowFilter(my_arr, 'an');
console.log('one', one);
console.log('two', two);
console.log('three', three);
https://jsfiddle.net/1321mzjw/
No need of lodash library use native JavaScript methods.
var data = [{
away: "Seattle Seahawks",
home: "Kansas City Chiefs",
}, {
away: "Houston Texans",
home: "San Francisco 49ers",
}, {
away: "Dallas Cowboys",
home: "Los Angeles Rams",
}];
console.log(
// filter the array
data.filter(function(v) {
// get all keys of the object
return Object.keys(v)
// iterate and check for any object property value cotains the string
.some(function(k) {
// convert to lowercase(to make it case insensitive) and check match
return v[k].toLowerCase().indexOf('49ers') > -1;
})
})
);
console.log(
data.filter(function(v) {
return Object.keys(v).some(function(k) {
return v[k].toLowerCase().indexOf('an') > -1;
})
})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With