swanson_ron swanson_ron - 5 months ago 26
Javascript Question

Underscore JS, find object which contains value in array

Im looking for a solution to find json object which contains a value in b. example: find objects which contain "jinx" in b.

sample data.
[{
id:1
a:"karma",
b:["jinx","caitlyn","tristana"]
},
{....},
{....}]

I understand underscore works better for key/value pairs but this would be of great help.

Thanks.

Answer

This will give you an array out of objects that contains all items from array in where b contains the element jinx:

var in = [...];

var out = _.filter(in, function(item) {
   return _.contains(item.b, 'jinx');
});