gpt4 book ai didi

javascript - 在 javascript 对象数组中查找其中一个属性与另一个数组中的项目不匹配的项目

转载 作者:行者123 更新时间:2023-11-28 13:27:24 28 4
gpt4 key购买 nike

假设我有两个数组,一个是对象,一个是简单的:

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 中的项目不匹配。

我应该回来:

result = [{id:2,name:'john'},{id:4,name:'pete'}]

我尝试过 $.grep、.filter 和 $.inArray 的各种组合,但遇到了困难。

最佳答案

你可以试试这个:

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 - 在 javascript 对象数组中查找其中一个属性与另一个数组中的项目不匹配的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28049138/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com