Updating the value of a specific property within an object in an array

I'm in the process of developing a stock trading application, and I have an empty array to store the stocks that are bought. Each time a stock is purchased, it adds an object to the array. If the same stock is bought again, I want to check for that specific stock in the array and only update its quantity. Otherwise, I want to add a new object to the array.

I've attempted to use a forEach loop and some functions, but I'm struggling to identify the current element in the array that has already been bought so I can update its quantity. I know how to calculate the quantity to be added, but I can't pinpoint the specific object to append it to.

The 'item' variable represents the object that needs to be appended to the array, adding only the quantity if the object is already present in the array. Thanks!

stocks = [
        {id:0, name:'BMW', price:5, quantity:0},
        {id:1, name:'Google', price:20, quantity:0},
        {id:2, name:'IBM', price:34, quantity:0},
        {id:3, name:'Apple', price:15, quantity:0}
    ];
...
...
stockPortfolio = []
...
   //the item is 
        'ADD_PORTFOLIO_ITEM'(stockPortfolio , item){
      //check if item id already exists            
     // if not, create a new one            
            const arrayP = stockPortfolio;            
            const found = arrayP.some(el => el.name === item.name);
            if (found) {

            }
            else{

Answer №1

let searchResult = stockPortfolio.find(element => element.name === item.name);
if (searchResult) {
    // The search result contains the matching item
} else {
    // No match was found, so add it to the array
}

Answer №2

My solution is effective for me. If you encounter any challenges, feel free to reach out. I am modifying the original stockPortfolio array. To create a new array, use .slice() at the beginning of the 'addStock' function.

const stocks = [
        {id:0, name:'BMW', price:5 , quantity:0},
        {id:1, name:'Google',price:20, quantity:0},
        {id:2, name:'IBM', price:34, quantity:0},
        {id:3, name:'Apple', price:15,quantity:0}
    ];

let stockPortfolio = [ ];

function addStock(stockPortfolio , item) {
  let found = stockPortfolio .some(el => el.name === item.name)
  if (!found) {
     stockPortfolio.push(item);

  } else {
      for (var i = 0; i < stockPortfolio.length; i++) {
        if (stockPortfolio[i].name === item.name) {
          stockPortfolio[i].quantity += item.quantity;
        }
      };
  };
};

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

Navigating through Vue.js development environments using relative paths

I'm encountering difficulties with navigating paths between the development and production environments in a project involving Laravel and Vue.js. Regarding CSS files: In the development environment, using npm run hot requires absolute paths in URLs ...

Issue encountered when populating the list of orders along with an array of merchandise items

I am currently in the process of developing an e-commerce website using React, Node, and MongoDB. The order schema I created includes the cmdRef (string), the client ID, and an array of products (with product IDs and quantities) as shown in the code below: ...

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...

Instructions on how to send input from a React JS user interface to a Node.js service

I am a beginner in using React JS and have a general inquiry. Typically in React, the recommended approach is to create a state object for input controls and assign its value to that input before submission. This method works well when dealing with 2-5 con ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

What is the process for accessing and utilizing the value returned by a promise in a separate file?

I have developed a small project to demonstrate an issue. There are a total of 5 files in this project: - A container file that includes all the dependency injections. - A service file containing the necessary functions to be executed. - A controller fil ...

Is it possible to perform operations on arrays in Java similar to Matlab?

Is there a method to achieve the following task without the need to create a function or use a for loop? int[] ma = (3,4,4,5,6,7); ma += 5; This quick shortcut allows for adding 5 to all elements in the array, similar to the convenience provided by Matla ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

What is the process for transforming a python list containing multiple 3D arrays into a single 3D array with a predefined shape?

I have a list called itemlist containing 25 3D Arrays, each with a shape of (128x128x3). My goal is to combine all these arrays into a single cohesive array, essentially creating an image. I anticipate the new shape to be (640, 640, 3), resulting in 5 row ...

Rendering a Subarray using Map in ReactJS

I have an object containing data structured like this: [{"groupid":"15","items":[ {"id":"42","something":"blah blah blah"}, {"id":"38","something":"blah blah blah"}]}, {"groupid":"7","items": [{"id":"86","something":"blah blah blah"}, {"id":"49","somethin ...

Creating responsive tabs that transition into a drop-down menu for mobile devices is a useful feature for

I am looking to create a responsive tab design that drops down like the example shown below: Desktop/Large Screen View https://i.stack.imgur.com/hiCYz.png Mobile View https://i.stack.imgur.com/gRxLv.png I have written some code for this, but I am unsure ...

The submit form and cordova functions are failing to trigger

I am encountering an issue where I cannot successfully call the submitForm() function when attempting to trigger it via ng-submit. The function does not execute as expected. How can I troubleshoot and resolve this problem? (function () { 'use str ...

I am encountering some difficulties with the functionality of the angularjs dialog

I've been attempting to integrate an AngularJS dialog feature into my application by following the examples provided on material.angularjs.org. However, despite copying everything accurately, I am unable to get it to function. Can anyone help identify ...

What's the best way to transfer a variable from a PHP file to a jQuery AJAX file so that it can be used as the URL parameter when sending

I am just starting out with javascript, jquery, and ajax. Unfortunately, I've encountered an issue where my code is not working as expected. Below, you can find a detailed description of my code and the problem at hand. If someone could offer some ass ...

What causes an "Undefined index" error in jQuery when making AJAX requests?

Whenever I make an AJAX request in my main.js file, I encounter the following error message: Undefined index: id in sqlinfo.php on line 13 I am puzzled because I believe that I am populating the request object correctly. What's even more perplexing i ...

Populating a two-dimensional array with randomly generated numbers using javascript

Apologies if this has been asked before, but I couldn't find any previous posts on the topic as I'm still fairly new to this site! Lately, I've been exploring game development using HTML5 and JavaScript and have gotten into creating tileset ...

Tips for utilizing jquery.load for fetching a section of an html document or an entire html file

I'm experimenting with jquery's load function to dynamically fetch and display HTML content, rather than using $.ajax(). I enjoy exploring the various features that jQuery offers and want to understand how each one works. Below is the code I am ...

Attempting to modify PHP query following submission of data via Axios in Vue application

Fetching a JSON object through a PHP query from a service known as BullHorn can be done like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentTy ...