[英]How to group elements to add amounts in array with Vue JavaScript
我有一個從 axios 調用中獲得的列表,我嘗試創建一個數組,其中具有相同 ID 的產品增加該產品的數量和小計,否則它們將按原樣添加。
但我總是得到數量 = 1.xx 和錯誤的總數,我不明白為什么或哪里有問題
let dataGroup = [];
resp.data.forEach((element)=>{
let indexElement = dataGroup.findIndex(elm => {
return (elm.product_id === element.product_id ) && element.print;
});
if(indexElement !== -1){
dataGroup[indexElement].total += parseFloat(element.total);
dataGroup[indexElement].count += parseInt(element.count);
roundNumber(dataGroup[indexElement].count,0);
roundNumber(dataGroup[indexElement].total,2);
}
else{
dataGroup.push(element);
}
});
功能
window.roundNumber = function(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
dataGroup 在第一個實例中是空的,一切都根據我從 axios 調用中收到的數據工作,例如在圖像中第一行我必須得到 9 數量但我收到 1.00,單位值是 35 應該是 9 * 53 在 ST,但它不是那樣的
axios 的響應
[
{
"id": 4,
"product_id": 1,
"count": "1.00",
"total": "35.00",
"print": 1
},
{
"id": 5,
"product_id": 1,
"count": "1.00",
"total": "35.00",
"print": 1
},
{
"id": 6,
"product_id": 1,
"count": "1.00",
"total": "35.00",
"print": 1
}
....
這里你有一些邏輯問題。 檢查這個(見代碼中的注釋):
resp.data.forEach((element)=>{ let indexElement = dataGroup.findIndex(elm => { return (elm.product_id === element.product_id ) && element.print; }); if(indexElement !== -1){ // first convert total/count to float/int then update in existing array element dataGroup[indexElement].total += roundNumber(parseFloat(element.total), 0); dataGroup[indexElement].count += roundNumber(parseInt(element.count), 2); } else { // need to convert total/count to float/int then push to dataGroup element.total = roundNumber(parseFloat(element.total), 0); element.count = roundNumber(parseInt(element.count), 2); dataGroup.push(element); } });
這是因為您初始化組中的項目的方式。 字符串值從服務器返回,然后您嘗試將它們添加到浮點數。 嘗試通過您的控制台運行它。
"35.00" + parseFloat("35.00")
要解決此問題,您必須首先將值初始化為浮點數。 取而代之的是:
dataGroup.push(element)
嘗試這個:
dataGroup.push({
id: element.id,
product_id: element.product_id,
total: parseInt(element.total),
count: parseFloat(element.count),
print: !!element.print,
});
看看這個小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.