我有一个产品数组,其字段名称为ID,品牌,价格,QtySold,值,其中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},
];


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

最佳答案

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





STACKBLITZ DEMO

09-19 19:48