我正在尝试创建一个股票交易者应用程序,并且我有一个空数组来购买股票。每个购买的股票都会向数组添加一个对象。如果再次购买了相同的股票,我要检查库存,然后仅将数量附加到相关的数组。否则我只想追加新对象。
我已经尝试过使用for Each循环和一些函数,但是我似乎无法获取已经购买的当前元素并仅更新其数量。我能够获取要添加的数量,但无法添加到该对象。
item是要附加到数组的对象。仅当对象已经在数组中时才是数量;谢谢!
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{
答案 0 :(得分:2)
const found = stockPortfolio.find(el => el.name === item.name);
if (found) {
// found contains the matched item
} else {
// no match found, add to array
}
答案 1 :(得分:1)
这对我有用。如果您遇到任何问题,请告诉我。我正在更改stockPortfolio
的原始数组。如果要返回新数组,请在函数'addStock'的开头使用.slice()
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;
}
};
};
};