在其中一个属性与另一个数组中的项目不匹配的javascript对象数组中查找项目 [英] find items in javascript object array where one of the properties does not match items in another array
本文介绍了在其中一个属性与另一个数组中的项目不匹配的javascript对象数组中查找项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有两个数组,一个对象,一个简单:
Say I have two arrays, one of objects, one simple:
var objArray = [{id:1,name:'fred'},{id:2,name:'john'},{id:3,name:'jane'},{id:4,name:'pete'}]
var simpleArray = [1,3]
我想返回一个仅包含objArray中项目的新数组id属性值(1、2、3等)与simpleArray中的项目不匹配。
I want to return a new array with just the items from objArray where the id property value (1,2,3 etc) does not match an item in the simpleArray.
我应该返回:
result = [{id:2,name:'john'},{id:4,name:'pete'}]
我尝试了$ .grep,.filter和$ .inArray的各种组合,但是却为此而苦苦挣扎。
I've tried various combinations of $.grep, .filter and $.inArray but struggling with this.
推荐答案
您可以尝试以下方法:
var results = [];
objArray.filter(function(item){
if(simpleArray.indexOf(item.id)>-1)
results.push(item);
})
请尝试以下代码段:
function Customer(id, name){
this.id=id;
this.name=name;
};
this.Customer.prototype.toString = function(){
return "[id: "+this.id+" name: "+this.name+"]";
}
var objArray = [ new Customer(1,'fred'), new Customer(2,'john'), new Customer(3,'jane'), new Customer(4,'pete')];
var simpleArray = [1,3];
var results = [];
objArray.filter(function(item){
if(simpleArray.indexOf(item.id)>-1)
results.push(item);
});
document.write(results)
这篇关于在其中一个属性与另一个数组中的项目不匹配的javascript对象数组中查找项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文