0

I have a product list retrieved via PHP and I was trying to compute the total quantity per product. I already grouped them using push in javascript. Now I want to achieve that it will compute the total value(QTY) based on the key(Product ID).

[{130493: 1}, {130493: 34}, {141364: 500}, {120798: 336}, {130493: 12} ];

Output should be:

[{130493: 47},{141364: 500},{120798: 336}]

My Code:

let get_list_items = document.querySelectorAll("#mta-product-list .product-list-item");
let get_qty_per_prod = [];
    get_list_items.forEach(item=>{
       let item_id = item.getAttribute("data-product-id").toString();
       let get_current_qty = item.querySelector(`[data-product-id='${item_id}'] .list-product-quantity`).value.toString();
       get_qty_per_prod.push({[item_id]:get_current_qty});
        
     });
     //get_qty_per_prod = sample output [{130493: 1}, {130493: 34}, {141364: 500}, {120798: 336}, {130493: 12} ];
     //trying to compute total per product here...              
     let total_qty = 0;
     let get_total_qty = [];
     if(get_qty_per_prod){
      get_qty_per_prod.forEach(totalQty=> {
       //console.log(totalQty);    
         if(productId){
               total_qty += parseInt(totalQty[productId]); 
               get_total_qty.push({[productId]:total_qty});
         }
                                                  
    });                          
     console.log(get_total_qty);
   }
Never Stop Learning
  • 755
  • 1
  • 10
  • 34
  • 1
    and [Javascript array of objects group and sum items](https://stackoverflow.com/questions/65059071/javascript-array-of-objects-group-and-sum-items) – pilchard Feb 16 '23 at 03:31

0 Answers0