Reputation: 419
myArray = [{'id':'73','foo':'bar 22'},
{'id':'45','foo':'bar'},
{'id':'46','foo':'area'},
{'id':'47','foo':'line'}]
var allbars = myArray && myArray.filter(function( obj ) {
return obj.foo == "bar";
});
After filtering i am able to get
allbars = [{'id':'45','foo':'bar'}]
but i need all bars exists in the foo key
Expected output is(in the key foo i have bar, bar22 both are expecting in the output but i can able to get only bar)
allbars = [{'id':'45','foo':'bar'}, {'id':'73','foo':'bar 22'}]
Upvotes: 1
Views: 48
Reputation: 15292
One can do it using regular expression
RegExp#test
.
const pattern = new RegExp('bar', 'i');
var allbars = myArray && myArray.filter(function( obj ) {
return pattern.test(obj.foo);
});
Upvotes: 0
Reputation: 9738
You should use .includes()
inside the filter condition
myArray = [{'id':'73','foo':'bar 22'},
{'id':'45','foo':'bar'},
{'id':'46','foo':'area'},
{'id':'47','foo':'line'}]
var allbars = myArray && myArray.filter(obj => obj.foo.includes("bar"));
console.log(allbars)
And if you want to make it browser compatible (IE) you may wanna use .indexOf()
myArray = [{'id':'73','foo':'bar 22'},
{'id':'45','foo':'bar'},
{'id':'46','foo':'area'},
{'id':'47','foo':'line'}]
var allbars = myArray && myArray.filter(obj => obj.foo.indexOf("bar") > -1);
console.log(allbars)
Upvotes: 2
Reputation: 171669
Use String#includes()
or String#indexOf()
instead of checking equality. Convert both values to lowercase or uppercase if wanting case insensitive match
var allbars = myArray && myArray.filter(function( obj ) {
return obj.foo.includes("bar");
});
Upvotes: 0