[Vuejs]-How to sum item's quantity separately in v-for(VueJS)

0👍

Finally!

Using filters in Vue, I get to this.

filters: {

   sumProducts: function(list) {
        var products= [];

          Object.keys(list).forEach(key => {
            var order = list[key];
            var orderDetail = order.detail;
                for(let i=0; i < orderDetail.length; i++) {
                    var item = orderDetail[i];
                      if(products[item.title] != undefined){
                        products[item.title] += item.quantity;
                      } else {
                        products[item.title] = item.quantity;
                      }
                }
          }) ;
          return products;
}
}

0👍

First of all, use script tags or external javascript files with .js extension. then, you would most likely not need more help in this case

And yes, maybe .reduce can solve your problem as Adriano Resende says

0👍

Try to use something like this function to get the sums for each product then show:

var list = {
    "Order1" : {
    "detail" : [ { "quantity" : 1,
                    "title" : "Tomato"
                  }, 
                  { "quantity" : 1,
                    "title" : "Banana"
                  } ],
                },
    "Order2" : {
    "detail" : [ { "quantity" : 1,
                    "title" : "Banana"
                  }]
                },
    "Order3" : {
    "detail" : [ { "quantity" : 1,
                    "title" : "Tomato"
                  }]
                },
          };

function sum_products(list){
  var products = [];
    for(var order in list){
        var orderDetail = list[order].detail;
        for(var i in orderDetail){
          var item = orderDetail[i];
          if(products[item.title] != undefined){
            products[item.title] += item.quantity;
          } else {
            products[item.title] = item.quantity;
          }
        }
    }
    return products;
}
console.log(sum_products(list));

Leave a comment