Change the element of an object within an array of objects

My itemCollection class is designed to store information about purchases. It includes an array called _items where the purchases are stored. When a user adds a new purchase to their cart, the class utilizes the addItem method. This method checks if the item is already in the _items property and either increments the quantity or adds a new item to the array.

The issue I am facing is that instead of adding a new item to the array when a different item is chosen, it simply continues to increment the quantity property of the first item that was added.

cartCollection class (object):

var cartCollection = {
    _items: [],
    addItem: function(obj) {
      'use strict';
      var purchase = {
        item: {
          id: obj.id,
          name: obj.name,
          price: obj.price
        },
        thisItemTotal: obj.price,
        quantity: 1
      };
      var result = _.findWhere(this._items, purchase.item.id);
      console.log(result);
      if (typeof result != 'undefined') {
        //console.log(result);
        var index = _.findIndex(this._items, {
          id: result.item.id
        });
        //console.log(index);
        result.quantity++;
        this._items[index] = result;
        this._itemTotalPrice();
      } else if (typeof result === 'undefined') {
        console.log("I'm being called!");
        this._items.push(purchase);
        console.log(this._items);
      }
    },
    ...

Answer №1

When working with a purchase that doesn't have an ID, but contains an "item" with an ID, the correct way to find the item is:

var result = _.find(this._items, function(item) {
   return item.item.id == purchase.item.id;
});

To avoid confusion, it may be beneficial to rename _items to _purchases

The revised code could look like this:

addItem: function(obj) {
  'use strict';
  var purchase = {
    item: _.pick(obj, 'id', 'name', 'price')
    thisItemTotal: obj.price,
    quantity: 1
  };

  var result = _.find(this._items, function(item) {
    return item.item.id == purchase.item.id;
  });

  console.log(result);

  if (result) {
    result.quantity++;
    this._itemTotalPrice();
  }
  else {
    console.log("I was called!");
    this._items.push(purchase);
    console.log(this._items);
  }
},

Answer №2

Your findWhere function needs a fix. Here's the correct way to code it:

var result = _.findWhere(this._items, {id: purchase.item.id});

Wishing you success!

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

What is the process of accessing JSON data transmitted from a Express server in JavaScript?

Working with a node server, I've set up a client-server model, meaning the client connects to "localhost" and express generates a response based on certain logic. While I'm able to send a JSON object through the response, I'm unsure of how t ...

Reverberating documents from a directory

Looking to create an MP3 or audio page where users can upload files, have them stored in a folder, and then displayed on the page as playable audio files. The most recently uploaded files should appear at the top of the page. Currently, I have an upload ...

Save the result of the rpm -Va command to an array while preserving the spaces

I am trying to organize the results of the rpm -Va command into an array for further analysis. Ideally, I would like each line from the rpm output to be its own element in the array. Unfortunately, I have been unsuccessful in my attempts so far and could u ...

The MIME type 'text/html' is incompatible with stylesheet MIME type and is not supported

I have exhausted all possible solutions for the issue, from specifying the type for <link rel="stylesheet" href="./style.css" /> to using app.use(express.static('public')), but unfortunately, none of them seem to resolve the problem. index ...

Encountered an error with the Angular 1 component router: Unable to access property 'startsWith' as it is undefined

I've been utilizing the Angular 1 component router and encountering some strange issues. Everything works perfectly when I run the website locally, but as soon as I try to access it from another PC, I'm hit with a JavaScript error. It keeps th ...

Preventing pop-up windows from appearing when triggered by a mouse click event

I am looking for a solution to trigger a popup window when a user right-clicks on a specific area. Here is the current code I am using: $("#popup").bind('mousedown', function(e) { var w; if(e.which==3) { w=window.open('link& ...

How can one retrieve specific key values from all random IDs in a Realtime Database, using Firebase functions with JavaScript?

Looking to retrieve the locations of all users in order to find nearest friends Here is an example of my Firebase Real-time database structure: ---> users ---> userRandomId ---> name: location :[12312,213123] ---> ...

The code inside the if statement is somehow executing even when the if statement is not true

Similar Question: Issue with jQuery function running at inappropriate times I've spent several hours trying to figure out why my function isn't working properly. I have a function inside an if ($window.width() < 1000) statement, but it se ...

Using setTimeout within the useEffect hook

I've been working on a script that should display a different page from an array every 5 seconds. It seems to be mostly working, but sometimes the page doesn't switch exactly every 5 seconds - it might take 10 or even 15 seconds. My suspicion is ...

Tips for dividing the elements of an array by 4 using Javascript or ReactJS

I have a large array of items that I need to organize into 4 sections in order to improve the display on my user interface. The array contains up to 20 objects, and my objective is to create 4 separate arrays each containing 5 objects. let attributes = [ ...

Continuously encountering IndexErrors while attempting to manipulate char arrays

Currently in the midst of a simulation project, I have a piece of code that organizes data into an array in a particular way: [['_' '_' 'F' '_' '_'] ['_' '_' '_' '_&apos ...

Exploring the contrast between positive and negative numbers in javascript

I am facing a unique challenge with my Javascript function that counts the number of sorted numbers in an array. Strangely, it seems to work perfectly fine for positive numbers, but when negative numbers are involved, the function treats them as if they ...

One particular item in the list does not conform to the same formatting as the others

Having a formatting issue with the indexLink when populating an unordered list with links. Can't seem to dedent it properly no matter what I try. Here's the javascript snippet: function addCrumb() { /* reads from localStorage and determines wh ...

Adding values separated by semicolons in JavaScript

I am facing an issue with a column named priclmdetailli55 in a file. This column can have no value, one value, or two values separated by a semicolon. I want to sum the values if they are separated by a semicolon. This is my current approach: var str = ...

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

How can I change the color of a designated column in a Google stacked bar chart by clicking a button?

I am in the process of creating a website that compares incoming students at my university across different academic years. We have successfully implemented a pie chart to display data for the selected year. Now, we aim to include a stacked bar chart next ...

Utilizing ScrollView Component in React Native

I have developed a simple app that displays a collection of images with titles, resembling a film gallery where all available films can be viewed. However, I encountered an issue when trying to implement the ScrollView element as it does not allow for scro ...

What is the reason for the method returning "System.String[ ]" instead of returning all the elements within the array?

wordlist() function is supposed to return a string array copied from a field in a struct. However, the issue is that this function returns System.String[ ] instead of returning all the objects in the array. I attempted to use foreach, but it seems that&apo ...

Using CSS3 translate will result in children becoming relatively positioned

I am facing an issue with a sidebar that contains 2 divs. <div class="sectionsContainer clearfix"><-- Sidebar --> <div class="leftSection pull-left"> <p>Maor</p> </div> <div class="rightSection pu ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...