user9883888
user9883888

Reputation: 419

how to filter based on key from array using javascript?

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

Answers (3)

RIYAJ KHAN
RIYAJ KHAN

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

Chiller
Chiller

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

charlietfl
charlietfl

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

Related Questions