我有两个数组:
allLabBranches = {0:{labbranchid: "1", labname: "Main Branch"}, 1 :{labbranchid: "2", labname: "Gulberg branch"}, 2: {labbranchid: "3", labname: "Shahdara Branch"}};
admnuserbrnchs = {0: 1, 1: 2};
我想删除那些id与admnuserbrnchs
元素的元素不匹配的分支。我目前的代码如下:
if(allLabBranches.length >= admnuserbrnchs.length ){
for(var i =0; i < allLabBranches.length; i++){
for(var j =0; j < admnuserbrnchs.length; j++){
if(allLabBranches[i].labbranchid != admnuserbrnchs[j]){
allLabBranches.splice(i, 1);
}
}
}
}
但是,结果是错误的。
答案 0 :(得分:0)
您可以使用.filter
和.includes
来实现此目标。
var allLabBranches = {
0: {
labbranchid: "1",
labname: "Main Branch"
},
1: {
labbranchid: "2",
labname: "Gulberg branch"
},
2: {
labbranchid: "3",
labname: "Shahdara Branch"
}
};
var admnuserbrnchs = {
0: 1,
1: 2
};
//Convert the objects to arrays
allLabBranches = Object.values(allLabBranches);
admnuserbrnchs = Object.values(admnuserbrnchs);
//Filter array
var newBranches = allLabBranches.filter(function(v, i) {
return admnuserbrnchs.includes(Number(v.labbranchid)) ? true : false
});
console.log(newBranches);
&#13;