开发者

Filter javascript object array by string array

I have an array of objects, like this:

var companies = [
    { "name" : "Company 1",
      "logo" : "/logo.gif" },
    { "name" : "Company 2",
      "logo" : "/logo2.gif" },
    { "name" : "Company 3",
      "logo" : "/logo3.gif" } ];

I want to filter this array to get only values which have a name which exists in another array:

var myCompanies = [ "Company 1", "Company 3" ];

In this example, the data to be returned would be:

var companies = [
    { "name" : "Company 1",
      "logo" : "/logo.gif" },
    { "name" : "Company 3",
      "logo" 开发者_Go百科: "/logo3.gif" } ];

What's the best way to do this?


You can use $.grep() to get a new, filtered array, like this

var result = $.grep(companies, function(e) { 
               return $.inArray(e.name, myCompanies) != -1;
             });

You can test it here. Note that this performs much better than a $.each() loop, you can test it here: http://jsperf.com/each-vs-grep


By loop only..

var newArray = [];
$.each(companies, function(){
  if($.inArray(this.name, myCompanies) !== -1) newArray.push(this);
});

jQuery utilies are used here: jQuery.each() and jQuery.inArray()


This should to the job:

companies = $.map(companies,function(element){
  return ($.inArray(element.name,myCompanies)>-1?element:null)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜