简体   繁体   中英

How to update property of an particular object in array

I am trying to create a stock trader application and i have an empty array for the stocks bought. Each Stock bought adds an object to the array. if that same stock is bought again, I want to check for the stock and then append ONLY THE QUANTITY TO THAT RELEVANT ARRAY. else i want to append just the new object.

I have tried using the for Each loop and some function, but I cant seem to get the current element that has been bought already and update only its quantity. I am able to get the quantity to be added but not that specific object for it to be appended to.

item is the object to be appended to the array. only quantity if object is already in 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 the 
        'ADD_PORTFOLIO_ITEM'(stockPortfolio , item){
      //checking if an itemid  exists            
     // if not create  a new one            
            const arrayP = stockPortfolio            
            const found = arrayP.some(el => el.name === item.name);
            if (found) {

            }
            else{
const found = stockPortfolio.find(el => el.name === item.name);
if (found) {
    // found contains the matched item
} else {
    // no match found, add to array
}

This works for me. Let me know if you face any issues. I am changing the original array of stockPortfolio . If you wish to return a new array use .slice() at the start of the function 'addStock'

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;
        }
      };
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM