Home > Software design >  Group products and display quantity from the products array using Vue3
Group products and display quantity from the products array using Vue3

Time:12-08

I managed to count every repeated element in my array, now I just want to display only one and each product quantity quantity.

This is what I have now:

enter image description here

I have a function which I am exporting from a file called Helpers.js and then using in my Vue component.

Helpers.js:

export const groupBy = (arr, criteria) => {
    return arr.reduce((obj, item, index) => {
        const key = typeof criteria === 'function' ? criteria(item, index) : item[criteria];

        if (!obj.hasOwnProperty(key)) {
            obj[key] = [];
        }

        obj[key].push(item);
        return obj;
    }, {});
}

Orders Component:

import { groupBy } from "@/Utils/Helpers";
... rest of the component...

const groupedOrders = computed(() => groupBy(props.order.products, (product) => product.id));

This is in my template:

<div class="mt-5 mx-8" v-for="products in groupedOrders">
                {{ products.length }}
                <OrderItem  
                    v-for="(product, index) in products"
                    :product="product"
                    :key="index" 
                />
            </div>

This is the data which I am loggin in the console:

enter image description here

Any clue how to make it to show only one Modi and display the quantity, something like Modi (Qtty. 4)

CodePudding user response:

Currently, your code iterates through the products array that you create one tile for each product inside the products array due to the v-for on your OrderItem component.

To achieve what you want to have, you simply have to take one element of the array and output the array's length, rather than traversing through it.

<div class="mt-5 mx-8" v-for="(products, groupIndex) in groupedOrders">
    <OrderItem
        :product="products[0]"
        :key="groupIndex" 
        />
    <span>Quantity: {{ products.length }}</span>
</div>

Keep in mind, that you need to be sure, that the products array is not empty in order to access the first element without an error. If you use the grouping function you provided, this should be fine.

Now what this will most likely do, is add the quantity behind your product tile. In order to print the quantity inside your product tile, you need to provide it to your OrderItem component.

<OrderItem
        :product="products[0]"
        :key="groupIndex"
        :quantity="products.length"
        />

Then in OrderItem.vue:

... component stuff ...
props: [
    ... your other props ...
    'quantity',
    ... your other props ...
]

And in the OrderItem template, at the position of your liking:

<span v-if="quantity > 0"> Quantity: {{ quantity }} </span>

In case you do not provide quantity, the v-if condition will make sure, that you do not output the quantity text.

  • Related