In JavaScript, the object constructor fails to bundle items into cohesive groups

I recently discovered javascript object constructors and came across this interesting example while studying the topic. I experimented with it by adding items to a sample product page, and it worked well. However, I encountered an issue where if I added the same item twice, it would group them together and increase the quantity. But what if I want each item to be listed separately?

function Cart(oldcart) {
  this.items = oldcart.items || {};

  this.add = function (item, id) {
    var storeditem = this.items[id];
    if (!storeditem) {
      storeditem = this.items[id] = { item: item, qty: 0, price: 0 };
    }
    storeditem.qty++;
    storeditem.price = storeditem.item.itemprice * storeditem.qty;
  };
}

var cart = new Cart(req.session.cart ? req.session.cart : {});
cart.add(data, id);
req.session.cart = cart;

My interpretation of the code is that it first checks if the newly added item already exists in this.items based on its ID:

var storeditem = this.items[id];

If it doesn't exist, then it creates the item:

if (!storeditem) {
  storeditem = this.items[id] = { item: item, qty: 0, price: 0 };
}

However, if I want to list items separately instead of grouping them, how can I modify the this.add method? Simply replacing the line

this.items[id] = { item: item, qty: 0, price: 0 };

with this code causes the new item to replace the existing one. What am I missing in my approach? I prefer not to use jQuery for this task and would like to understand how to achieve it using pure javascript.

Answer №1

Your current approach involves storing each new item in an object. To better manage individual items, consider switching to an array structure instead. Transform this.items into an array from the beginning.

Within the add function, utilize the push method on this.items to include a new item in the array. By doing this, you will successfully append your item to the list. Subsequently, you can perform tasks such as calculating the total price, achieved by iterating through the list and summing up all the itemprice values.

function ShoppingCart(previousCart) {
  this.items = previousCart.items || [];
  this.total = previousCart.total || 0;
} 

ShoppingCart.prototype.add = function(item) {
  this.items.push(item);
  this.total = this.items.reduce(function(total, currentItem) {
    return total + currentItem.itemprice;
  }, 0);
};

var shoppingCart = new ShoppingCart({});
shoppingCart.add({ id: 52, name: 'Melon', itemprice: 3.20 });
shoppingCart.add({ id: 2, name: 'Banana', itemprice: 0.30 });
shoppingCart.add({ id: 2, name: 'Banana', itemprice: 0.30 });

console.log('Items in Cart:', Shoppingcart.items);
console.log('Total Price:', Shoppingcart.total);

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

Error: The Tabs component is expecting a different `value`. The Tab with the current `value` ("0") is not present in the document structure

I am encountering an issue while using MUI tabs. The error message I receive is as follows: MUI: The value assigned to the Tabs component is not valid. The Tab with this value ("0") does not exist in the document layout. Please ensure that the tab item is ...

Angular Cascade of Multiple Requests

I am currently working on a project where I need to develop a service that can take CSV data, convert it into rows, and then make API requests for each row, adding the formatted results to an output string. To explain further, my code (written in Coffeesc ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

Unable to utilize the post method in Node.js

<form class="ui form" action"/submit" method="post"> <div class="field"> <label>Time dedicated to studying:</label> <input type="number" name="study" placeholder="Total time spent on studies:"> ...

Picture goes missing from slideshow

I am currently using a CSS + Javascript slideshow on my website, inspired by an example from the W3Schools website. Here is the code I have adapted for my web application: $(document).ready(function() { var slideIndex = 1; function showSlides(n) { ...

What is the best way to show my button only when within a specific component?

Is there a way to display the Logout button on the same line as the title only when the user has reached the Home component? In simpler terms, I don't want the logout button to be visible all the time, especially when the user is at the login screen. ...

Saving the current language (i18n) in local storage using VueJS

I'm working on a Vue app that utilizes Vue Routers and the Vue $i18n plugin. Here's how I've structured my HTML: <div class="locale-changer"> <select v-model="this.$i18n.locale" class="btn"> ...

"Securing Your Web Application with Customized HTTP Headers

I'm currently working on setting up a POST request to a REST API (Cloudsight) with basic authorization. Here is the code I have so far: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.cloudsightapi.com/image_requests", true); xhr.setRequ ...

I need to inform users that this application is not accessible on devices with small screens

Showing this app on a small device is not supported, such as when the device width falls between 320px and 480px. ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Solving the Issue of Assigning a Random Background Color to a Dynamically Created Button from a Selection of Colors

Trying to create my own personal website through Kirby CMS has been both challenging and rewarding. One of the features I'm working on is a navigation menu that dynamically adds buttons for new pages added to the site. What I really want is for each b ...

Tips for eliminating redundancy in JavaScript when updating an UpdatePanel in ASP.NET

If JavaScript code is not functioning after the UpdatePanel has been refreshed, it needs to be handled properly. There are multiple ways to address this issue. One preferred method involves implementing the following: <script language="javascript" type ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

altering dimensions in three.js

My question may seem a bit silly, but it's about resolution in THREE.js. I have experience with OpenGL and some frameworks related to it, so naturally, I became interested in webGL and Three.js. After trying out some simple demos, I decided to create ...

Distinguishing Features of HTML, Canvas, and WebGL

Is there a way to draw images in WebGL with the same quality as HTML, even when downscaled? I've noticed that scaling down images in WebGL results in poor quality compared to HTML. After reading about 'Handling High DPI (Retina) displays in WebGL ...

What are alternative methods to prevent a div from expanding in width from the right side other than using position absolute?

Looking to create a div element that only expands from the left side as content is added? <div id="sent_message" style='background-color: #2b89cc; color: white; font-family: Arial,Helvetica, sans-serif; margin-top: 10px; display: ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...

Using flags to translate text on Google should not result in being redirected to another website

I have integrated Google's language picker with country flags into my WordPress template using the code below: <!-- Add English to Chinese (Simplified) BETA --> <a target="_blank" rel="nofollow" onclick="window.open('http://www.google. ...

Combining two objects retrieved using ngResource in AngularJS

Seeking guidance on merging two objects retrieved using ngressource. Every 5 seconds, I invoke my service to fetch a message and aim to append the new message with the older ones. The JSON message I receive: [ {"age": 0,"id": "my first tweet","name": "H ...

Tips for dynamically updating an input within a shadow DOM using code?

Snippet: https://jsfiddle.net/5zrwdjy7/2/ I'm currently working on automating keystrokes with a script within Cypress, however, the target website I am dealing with utilizes web components as inputs. These input elements are nested inside what is kno ...