Utilize Vue3 to categorize items and showcase the quantities from the product list

I successfully counted every repeated element in my array, now I just need to display only one of each product along with its quantity.

Here is the current progress:

https://i.sstatic.net/SBm64.png

I have a function that I'm exporting from a file named Helpers.js and then using it 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 what's 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 I am seeing in the console:

https://i.sstatic.net/AEZeX.png

Any idea on how to display only one "Modi" and show the quantity like Modi (Qtty. 4)?

Answer №1

At the moment, your code is looping through the products array to create a tile for each product within the array using the v-for on your OrderItem component.

To achieve your desired outcome, you simply need to grab one element from the array and display the length of the array instead of iterating 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>

It's important to ensure that the products array is not empty before trying to access the first element to avoid errors. If you are using the grouping function as provided, this shouldn't be an issue.

By implementing this change, the quantity will likely be appended after the product tile. To display the quantity inside your product tile, you'll need to pass 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, wherever you prefer:

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

If no quantity is provided, the v-if condition will ensure that the quantity text is not displayed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript: Generating multiple variables using a for loop?

Is there a way to dynamically create n variables a_1, a_2, a_3 ... a_n, where the value of n is determined during runtime? Attempting to use the following code would not produce the desired outcome: var n = prompt("Enter number of variables?"); for (i= ...

What is the reason my function is only operating with a single ID?

I'm attempting to create color-changing "squares" that change color when clicked. The first square changes color correctly, but when I click on the others, the color change only happens on the first square. var image_tracker = 'red'; fu ...

Validating RSS Feeds with Javascript

Hey, I'm looking to replicate something like this: I want to verify RSS feeds before submitting a form. <form name="form1" id="form1"> <input type="text" name="url" type="text" id="url" /> <input type="submit" name="submit" id="bu ...

Inject a heavy dose of Vue into your project

**I'm trying to implement the provide/inject logic in Vue. In my 'App.vue' component, I have defined the 'firstName' input as a string "John", and I want to display this value when the child component 'Step1' is created. ...

In Angular 5, what is the best way to transform an array into an object and cycle through a list of

JSON: The JSON I have contains a list of userids that I want to iterate through, but I'm having trouble fetching the content in a list format. { "data": { "items": [ { "regions": "India", "owner ...

Is it possible to utilize gulp to eliminate all require.js define([...]) wrappers throughout the codebase?

Is it possible to test my app without using require.js in order to assess the performance and file size if all files were concatenated into a single one? I'm contemplating using gulp to gather all *.js files in the app, running a gulp-replace to elim ...

Cleaning up webpage content by removing specific characters using Python's Selenium

Currently, I am using Selenium with Firefox in Python and facing a challenge while matching elements on a webpage based on keywords from a list. To ensure successful element lookup, I need to remove special characters like ® and ™ from the web page. Un ...

Transferring the value of a TextBox to another TextBox in ASP.NET across multiple rows

I have around 10 rows where I need to duplicate the value of one TextBox into another. A specific ID can be assigned to the first TextBox to achieve this, but I am seeking a more general function that can copy TextBox values in each row in ASP.NET. This i ...

Utilize ng-checked in AngularJS to bind all values from an array to checkboxes

I'm working on a project where I need to bind the name and age of a person using checkboxes, with the data looped through ng-repeat. However, I seem to be able to only get the "name" from the array, not the "age". Can someone please help me find my mi ...

Exploring the power of Laravel9 and Vue2 collaboration

I followed the steps below to set up Laravel and Vuejs: Ran the command: laravel new blog Installed laravel/ui using composer: composer require laravel/ui Used php artisan ui vue command Installed vue-router: npm install vue-router Executed npm ...

What steps are involved in setting up a search results page for example.com/s/keyword?

app.js app.get('/results',showResult) var express = require('express') var n = req.query.query; mysql_crawl.query('SELECT prod_name, full_price FROM `xxx` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, p ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

Instructions for implementing a Back button that takes you directly to the text or link you clicked on to view an image

My goal is to have multiple anchor links within text, each linking to a specific image on the same page. Once the user views the image, I want them to be able to click a 'Back' button that will take them back to where they left off in the text. ...

Is randomly pairing 2 datapairs after slicing a JSON array easy or challenging?

There is a JSON file containing an unlimited number of users [{ "fname": "Hubert", "lname": "Maier", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bd ...

Deleting items from an array in ReactJS

When retrieving a list of users from AWS Cognito, everything works flawlessly. However, the task of iterating over this array and removing users that do not match a specific Client ID is where I'm facing difficulties. What am I doing wrong in this sc ...

JavaScript AJAX Event Listener

Currently seeking a way to intercept ajax events in JavaScript before any Ajax method is triggered. While there is an ajaxListener in JQuery that could work if all the ajax requests were from JQuery, unfortunately, they are not. So the question remains: ho ...

Tips for formatting HTML-escaped content in Vue 2 and Vue 3

Currently, I am utilizing user-generated data in a Vue application and the default behavior of html-escaping the data works perfectly. However, I now wish to enable users to search through this data and highlight the matching text in the search results. Th ...

React does not allow objects as child elements. Instead, render a collection of children by using an array

Encountering an error with this React class Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead. Is there anything amiss here? I am passing the movies ...

Insert the picture into an HTML document and retrieve the image file location

I successfully used <input type="file" accept="image/*"> to upload an image and then applied base64 encoding of the image in the onload callback function of a FileReader instance. However, I encountered a problem when trying to assign this base64 enc ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...