Search code examples
javascriptvue.jsv-for

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


I'm learning to code(really noob) with VueJS and I got really stuck here

I have a list of orders, and I want to sum the quantity of each item apart. The only access to the items is through v-for.

<tr>

<td data-th="list">

<tr v-for="(order,key) in list" :order="order" :key="key">

<li v-for="(item,key) in order.detail" :item="item" :key="item.title">{{ item.quantity }} {{ item.title }} </li> 

</tr>
</td>
    </tr>

The data is organized like this

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

Now I'm getting something like this:

1 Tomato
1 Banana
1 Banana
1 Tomato

But I want to get this:
2 Banana
2 Tomato


Solution

  • 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;
    }
    }