1
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'}]
1
  • Try indexOf('bar') Commented Jun 3, 2018 at 13:52

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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");
});

Comments

0

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);
    });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.