我有一个对象数组,如下所示:
var companies = [
{ "name" : "Company 1",
"logo" : "/logo.gif" },
{ "name" : "Company 2",
"logo" : "/logo2.gif" },
{ "name" : "Company 3",
"logo" : "/logo3.gif" } ];
我想过滤此数组以仅获取具有另一个数组中存在的名称的值:
var myCompanies = [ "Company 1", "Company 3" ];
在此示例中,要返回的数据为:
var companies = [
{ "name" : "Company 1",
"logo" : "/logo.gif" },
{ "name" : "Company 3",
"logo" : "/logo3.gif" } ];
最好的方法是什么?
答案 0 :(得分:7)
您可以使用$.grep()
获取新的已过滤数组,例如
var result = $.grep(companies, function(e) {
return $.inArray(e.name, myCompanies) != -1;
});
You can test it here。请注意,这比$.each()
循环要好得多,您可以在此处进行测试:http://jsperf.com/each-vs-grep
答案 1 :(得分:1)
仅循环..
var newArray = [];
$.each(companies, function(){
if($.inArray(this.name, myCompanies) !== -1) newArray.push(this);
});
此处使用jQuery实用程序:jQuery.each()和jQuery.inArray()
答案 2 :(得分:0)
这应该是工作:
companies = $.map(companies,function(element){
return ($.inArray(element.name,myCompanies)>-1?element:null)
}