I am using UnderscoreJs
in my project. I have to filter an array containing object having properties. I need to filter based on the values. The value can be of any property of the object. ex: "mini" should fetch both "toyota" and "Honda" since "mini" is present as part of both the objects
[{ name:"Toyota minivan", id:"506", size: "large" }, { name:"Honda Civic", id:"619", size: "mini" }]
How to do using Underscore. I have tried the following approach but not working.
var searchStr="mini";
var evens = _.filter([arrayData], function(obj){ return _.contains(obj, searchStr); });
Can you please let me know where I am going wrong?
I am using UnderscoreJs
in my project. I have to filter an array containing object having properties. I need to filter based on the values. The value can be of any property of the object. ex: "mini" should fetch both "toyota" and "Honda" since "mini" is present as part of both the objects
[{ name:"Toyota minivan", id:"506", size: "large" }, { name:"Honda Civic", id:"619", size: "mini" }]
How to do using Underscore. I have tried the following approach but not working.
var searchStr="mini";
var evens = _.filter([arrayData], function(obj){ return _.contains(obj, searchStr); });
Can you please let me know where I am going wrong?
Share asked Sep 3, 2014 at 11:05 zilcuanuzilcuanu 3,73513 gold badges60 silver badges119 bronze badges 02 Answers
Reset to default 4_.contains
only works on arrays, so you need to grab the values from each object first and then check if any of them contain the search string. I've used some
in this example, together with indexOf
to match the string.
var searchStr="mini";
var mini = _.filter(arr, function (obj) {
return _.values(obj).some(function (el) {
return el.indexOf(searchStr) > -1;
});
});
DEMO
Well, I have done this with simple if condition so that in future if you want to list mini in one array and large in one array so you can do easily. I have checked the object property if matched then assigned to new list. here is my code. and check out demo here fiddle
var list=[{ name:"Toyota minivan", id:"506", size: "large" },
{ name:"Honda Civic", id:"619", size: "mini" },
{name:"zen",id:"606",size:"mini"}];
var result=_.filter(list, function(obj){
if(obj.size=='mini'){
var matchedcars=obj;
console.log("result"+JSON.stringify(matchedcars));
}
return matchedcars;
});
alert("result"+JSON.stringify(result));