0

我有一个产品数组,其字段名称为 ID、品牌、价格、数量销售、价值,其中价值 = 价格 * 数量出售,最后我需要显示商品数量、销售总量和总销售价值

 @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},
];

需要显示产品数量、销售数量和销售价值总和

4

4 回答 4

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

堆栈闪电战演示

于 2019-02-14T18:12:56.933 回答
1

要么像@Sajeetharan 发布的简单减少,要么使用像 lodash 这样的实用库:

this.numberOfProducts = allProduct.length;
this.sumQtySold = _.sumBy(allProduct, product => product.qtySold);
this.sales = _.sumBy(allProduct, product => product.qtySold * product.price);
于 2019-02-14T18:15:08.407 回答
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;
}}}

上面的代码对我有用。它只是通过使用循环而不是其他术语来总结值。

于 2019-02-16T06:48:10.750 回答
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);

于 2019-02-14T18:20:21.467 回答