最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - filtering matching values from list of object using underscore - Stack Overflow

programmeradmin3浏览0评论

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 0
Add a ment  | 

2 Answers 2

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));
发布评论

评论列表(0)

  1. 暂无评论