var arr=[{"itemId":null,"basicItemId":1228,"itemName":"维他柠檬…10ml","unit":null,"costPrice":null,"typeId":null},
{"itemId":null,"basicItemId":1228,"itemName":"维他柠檬…10ml","unit":null,"costPrice":null,"typeId":null},
{"itemId":null,"basicItemId":1238,"itemName":"红牛","price":5.98,"icon":"","standard":"250ml","unit":null,"costPrice":null,"typeId":null}]
var items = [];
function addItem(newItem){
var exists = false;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.basicItemId == newItem.basicItemId) {
exists = true;
item.num = item.num+1;
break;
}
}
if(!exists){
newItem.num = 1;
items.push(newItem);
}
}
$.each(arr,function(index,val){
addItem(arr[index])
})
console.info(items);
整理后:
function add (arrArr) {
var shopCarItem = []
function addItem(newItem, exists = false) { //处理重复数据
shopCarItem.forEach(item => {
if (item && item.basicItemId == newItem.basicItemId) {
exists = true;
item.num += 1;
item.totalPrice = item.num * item.price //增加商品总价字段
}
});
if (exists) {
return
} else {
newItem.num = 1;
newItem.totalPrice = newItem.num * newItem.price //增加商品总价字段
shopCarItem.push(newItem);
}
}
arrArr.forEach((item, key) => {
addItem((arrArr[key]))
})
console.log(shopCarItem);
}
add(arrArr)