Combine the values of identical keys from multiple objects in an array by utilizing the forEach method in JavaScript

I am currently working on refining a shopping basket function with Vue JS. One of the key features I need to implement is a subtotal calculation that multiplies the price and quantity values for each item and then combines them to create an overall subtotal.

dataSet: [
  {
  "instock" : '',
  "price": 49,
  "qty": 1,
  "subTotal": '' 
  },
  {
  "instock" : '',
  "price": 29,
  "qty": 1,
  "subTotal" : '',
  },
]

Initially, I was able to retrieve the 'price' and 'qty' values using a forEach loop in the object array like this:

getSubTotal(dataSet) {    
   this.dataSet.forEach(function(data) {
   console.log(data.price)
})
console
49
29

While I successfully retrieved the price values, they were returned individually rather than as part of an array. The challenge I am facing now is how to return them as [49, 29] so that I can easily add them together to calculate the total. Hard-coding by index or adding them separately is not ideal for scalability, especially when new clothing items are added to the object array.

Any suggestions, feedback, or assistance would be greatly appreciated!

Answer №1

calculateTotal(dataSet) {    
   return this.dataSet.map(function(item) {
     return item.price;
})

Answer №2

After some investigation, I successfully managed to solve this problem.

dataSet: [
 {
 "price": 49,
 "qty": 1,
 },
 {
 "price": 29,
 "qty": 1,
 },
]

subTotals(data) {
  const calcArray = [data.price, data.qty];
  return calcArray.reduce((a,b)=> {
    //performing the calculation of multiplying price by quantity for subtotal
    return a*b;
  });
}

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

Automatically insert nested object keys and values from jQuery into their respective div elements

Below is a sample object that I am working with: "experience": { "1": { "jobtitle": "job_title", "companyname": "company_name", "companytown": "company_town", "companycountry": "company_country", "summary": "Sum ...

What changes occurred to module file names following the process of minification?

I'm currently troubleshooting an issue with this particular code snippet: import globalComponents from './global-components'; // ... globalComponents.forEach((component) => { // eslint-disable-next-line no-underscore-da ...

chaotic telerik editor arrangement

I have incorporated the Rad Editor into my ASP.NET page. <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <telerik:RadEditor ID="reSummery" runat="server" > </telerik:RadEditor> Despite not referencing ...

How can I extract the width of an uploaded image and verify it using JavaScript?

Is it possible to retrieve the image width through upload using PHP and then validate it in JavaScript? $_FILES['image'] If the image size is not equal to 560px, can we return false and display an alert message using JavaScript? Also, I am won ...

A guide to correctly importing a Json File into Three.js

I've been working on some cool projects in Blender and wanted to showcase one using threejs. However, I'm facing an issue where the object isn't displaying properly. Can someone guide me on how to correctly load a JSON file with keyframe ani ...

Obtain the current date using Moment JS in JavaScript

Here is a scenario with code : let currentTime = moment(); console.log(currentTime.format()); // 2019-11-25T20:23:50+02:00 console.log(currentTime.toDate()); // 2019-11-25T18:23:50.916Z After applying the timezone change on Heroku using the command ...

"The variables in the .env file are not reflecting the latest updates. What is the best way

Currently, I am in the process of developing an application using Quasar (Vue) where I have stored my database keys in a .env file. Recently, I encountered an issue when attempting to switch to another instance and updating the keys in the env file. Despit ...

Effortless Inertia Scrolling Implemented in Next.js

My search for achieving smooth inertia scrolling in next.js has left me unimpressed with the available solutions, as they either lack performance or come with some drawback. This medium article and sandbox demo provided a choppy experience, While this jav ...

Iterate through the array and generate a ListItem component for every element

Currently, I am facing an issue where only the ListSubheader is being displayed in my code. Despite passing an array named tools and trying to loop through it to create ListItem elements based on each item's properties, no buttons are displaying. I su ...

An AJAX request will only occur if there is an alert triggered on a particular computer

Here's an interesting issue I encountered with my company's CMS newsletter system. It seems that the AJAX call to send an email works flawlessly in all modern browsers and operating systems, except for one client. This particular client is using ...

Utilizing the content of an HTML element within Ruby embedded code - a comprehensive guide

Below is the code snippet in question: <% @groups.each do |group| %> <tr> <td id="groupid"><%= group.id %></td> <td><a href="#dialog" name="modal"><%= group.title %></a></td> </tr> &l ...

Exploring the World of D3.js with an Interactive Example

Struggling to grasp D3, I'm having difficulty executing the circle example. http://mbostock.github.com/d3/tutorial/circle.html I aim to run the part where the circles change colors and sizes. I simply copied and pasted the example but can't fi ...

Struggling with implementing basic i18n and dynamic routing functionality in Next.js

Despite reading the Next.js documentation, completing the tutorial, and reviewing numerous examples, I am still struggling to accomplish a straightforward task with Next.js. In my application, I have two locales: en and de. The route structure is as foll ...

Pop-up with a unique MediaBox design

Last week, I inquired about window pop-ups and have been brainstorming alternatives. One idea I had is to use mediabox/lightbox style pop-ups. Would it be feasible to create a link that opens a mediabox window off to the side when clicked? Users could dra ...

Running the command "npm start" is resulting in an error message stating: "ENOENT: no such file or directory ... package.json"

After successfully creating a React app using NPX, I encountered an issue when trying to run npm start. The error message that appeared is as follows: $ npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\Administrateur.TE ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

What is the method for incorporating PHP's header() function within PayPal JavaScript code?

I'm currently working on integrating Paypal with my website and I've run into some issues handling the various messages sent by Paypal, such as success, failed, and cancelled transactions. Below is a snippet of the Paypal JS code where it manage ...

Having issues setting a property value on a Mongoose result in a Node.js application

Hello there, I am currently working with a MongoDB object retrieved via a findById method, and I need to convert the _id within this object from an ObjectID type to a string. I have developed the following function: student: async (parent, { _id }, ...

Sorting in MongoDB v3.6 is a breeze with the powerful capabilities that the

I'm encountering an issue with arranging the most recently added item in a list of objects/items to display at the top. It's similar to a job board where I want the newest jobs to appear at the top rather than at the bottom. I attempted to use Po ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...