简体   繁体   English

按字符串数组过滤javascript对象数组

[英]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" : "/logo3.gif" } ];

What's the best way to do this? 最好的方法是什么?

You can use $.grep() to get a new, filtered array, like this 您可以使用$.grep()来获取一个新的过滤数组,就像这样

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 请注意,这比$.each()循环要好得多,你可以在这里测试它: http$.each()

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() 这里使用jQuery 实用程序jQuery.each()jQuery.inArray()

This should to the job: 这应该是工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM