我试图展示存在于一个api中的客户端的优惠券。如果一个(或'n')优惠券存在于另一个api中,计算使用的优惠券,我必须从列表中删除使用的优惠券或使用的优惠券。使用过的优惠券的api响应如下:
{
"State": 200,
"Response": [
{
"IdInvoiceRequest": 104,
"Coupons": [
{
"IdCoupon": 77236,
"Code": "11#E5ZQHZ-GNH"
},
{
"IdCoupon": 77237,
"Code": "12#WM96FY-NGE"
},
{
"IdCoupon": 77239,
"Code": "14#BH92BA-E6N"
},
{
"IdCoupon": 77240,
"Code": "15#FWXNR4-XHP"
},
{
"IdCoupon": 77241,
"Code": "16#7FK5F8-TKM"
}
]
},
{
"IdInvoiceRequest": 143,
"Coupons": [
{
"IdCoupon": 77238,
"Code": "13#BN5MZB-VJ9"
}
]
}
],
"Message": "Informacion correcta",
"TotalRows": 0,
"IsCorrect": true}
当我试图消除使用过的优惠券时,问题就来了。到目前为止我的代码是:
function validExist() {
vm.getSelected =
couponExist.get({
idOrder: vm.idOrder
}).$promise.then(function(data) {
for (var i = 0; i < data.Response.length; i++) {
data.Response[i].Select = vm.exist;
console.log(vm.exist);
}
vm.otherF = vm.coupons
for (var i = 0; i < data.Response.length; i++) {
data.Response[i].Select = vm.isHere;
console.log(vm.isHere);
}
if (vm.exist == vm.isHere) {
vm.coupons.splice(vm.coupons.IdCoupon, i++);
};
});
}
当剪接作用时,只消除第一张优惠券,但其他的仍然一样,即使所有的优惠券都在使用的优惠券列表中。我能做什么来删除所有的优惠券?我听说过这样做的一种方法是使用'forEach‘o’don 'for',但我看不到光(叹气)。
你能帮帮我吗?
提前鸣谢。
发布于 2017-08-31 22:28:25
Array.prototype.splice
接受一个开始索引和要从数组中移除的项数。我不知道您的代码的其他部分应该做什么,但是下面是一个示例,说明如何从一个数组中查找项目并从另一个数组中删除它们:
var existingCoupons = [
{ IdCoupon: 111 },
{ IdCoupon: 222 },
{ IdCoupon: 333 },
{ IdCoupon: 444 },
{ IdCoupon: 555 }
];
var simulatedResponse = [{
IdInvoiceRequest: "abc",
Coupons: [
{ IdCoupon: 222 },
{ IdCoupon: 444 }
]
},{
IdInvoiceRequest: "def",
Coupons: [
{ IdCoupon: 555 }
]
}];
//Loop through the invoices in the response
for(var i=0; i<simulatedResponse.length; i++){
//Loop through the coupons in the invoice
for(var j=0; j<simulatedResponse[i].Coupons.length; j++){
//Loop through the existing coupons
for(var k=0; k<existingCoupons.length; k++){
//If the unique identifier matches...
if(existingCoupons[k].IdCoupon == simulatedResponse[i].Coupons[j].IdCoupon){
//Splice one existing coupon out of the array at the current index
existingCoupons.splice(k, 1);
break;
}
}
}
}
console.log(existingCoupons)
发布于 2017-08-31 22:26:41
让我们在您试图解决的问题的概念定义中添加一些明确性,然后选择实际的编程实现。
您似乎有两个列表,目标是从第一个列表中删除所有条目,第二个列表中存在这些条目。解决此问题的一个可能且非常简单的解决方案是创建第三个空列表,然后使用两个for
迭代循环(第一个列表的外部和第二个列表的内部循环)动态地只添加第一个列表中不存在的条目。除了明显的简单性外,这种方法还将提供近乎最优的计算性能。
希望这能帮上忙。
https://stackoverflow.com/questions/45990775
复制相似问题