我有一个包含名称ID,Brand,Price,QtySold,Value的产品数组,其中value = Price * qtySold,最后我需要显示商品数,已售总数量和总销售金额
@Component
({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
}`
export class AppComponent{
allProduct:Product[]=[
{Id:'P104', Brand:'Pepsi',Price:4,qtySold:22},
{Id:'C124', Brand:'Coke',Price:4,qtySold:26},
{Id:'M155', Brand:'Maggie',Price:6,qtySold:10},
{Id:'DM241', Brand:'Cadburys',Price:10,qtySold:15},
{Id:'5S118', Brand:'5 Star',Price:8,qtySold:8},
];
需要显示产品数量,销售数量总和和销售价值总和
答案 0 :(得分:3)
您的ngOninit中将需要以下内容
let products = [
{
"Id": "P104",
"Brand": "Pepsi",
"Price": 4,
"qtySold": 22
},
{
"Id": "C124",
"Brand": "Coke",
"Price": 4,
"qtySold": 26
},
{
"Id": "M155",
"Brand": "Maggie",
"Price": 6,
"qtySold": 10
},
{
"Id": "DM241",
"Brand": "Cadburys",
"Price": 10,
"qtySold": 15
},
{
"Id": "5S118",
"Brand": "5 Star",
"Price": 8,
"qtySold": 8
}
];
let productsCount = products.length;
let qtySold = products.reduce((a, b) => +a + +b.qtySold, 0);
let sales = products.reduce((a, b) => +a + +b.Price, 0);
console.log(productsCount);
console.log(qtySold);
console.log(sales);
答案 1 :(得分:1)
要么像@Sajeetharan这样的简单reduce发布,要么使用像lodash这样的util库:
this.numberOfProducts = allProduct.length;
this.sumQtySold = _.sumBy(allProduct, product => product.qtySold);
this.sales = _.sumBy(allProduct, product => product.qtySold * product.price);
答案 2 :(得分:0)
另一种实现方式:
const beverageSales = [
{
"Id": "P104",
"Brand": "Pepsi",
"Price": 4,
"qtySold": 22
},
{
"Id": "C124",
"Brand": "Coke",
"Price": 4,
"qtySold": 26
},
{
"Id": "M155",
"Brand": "Maggie",
"Price": 6,
"qtySold": 10
},
{
"Id": "DM241",
"Brand": "Cadburys",
"Price": 10,
"qtySold": 15
},
{
"Id": "5S118",
"Brand": "5 Star",
"Price": 8,
"qtySold": 8
}
];
let itemsSold = 0;
let quantitySold = 0;
let netSales = 0;
beverageSales.forEach(sale => {
itemsSold += 1;
quantitySold += sale.qtySold;
netSales += sale.Price * sale.qtySold;
});
console.log('items sold', itemsSold);
console.log('quantity sold', quantitySold);
console.log('net sales', netSales);
答案 3 :(得分:0)
productCount : number=0;
quantitySold : number=0;
sales : number=0;
sold : number=0;
ngOnInit(){
for(let temp of this.allProduct){
this.productCount += 1;
this.quantitySold += temp.qtySold;
this.sales += temp.Price * temp.qtySold;
if(temp.qtySold>0){
this.sold += 1;
}}}
上面的代码为我工作,仅通过使用Loops而不使用其他术语就可以对这些值求和。