Angular 6如何从对象数组中基于相同值获取特定列的计数

时间:2019-05-29 18:42:51

标签: html angular typescript

我有一个对象数组,我也在打字稿中使用foreach循环。根据我的数组,它包含2个列,其值分别为Progress:100和其他的列小于100.所以这里我需要计算列数具有进度:100,例如,在这里应该是2。另外,我需要获取具有进度值小于或不是100的所有列的计数。例如,在这里2。然后我需要附加到div中。添加不计数。这是下面的代码

app.component.html

<div>Progress : 2{{count}}</div><div>completed : 2{{count}}</div> 

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}

4 个答案:

答案 0 :(得分:2)

实际上,您是在count中添加进度值。请尝试这个。

ngOnInit(){
   let progress_count=0;
   let completed_count=0;
   this.array.forEach((item, index) => {
   if (item.progress == 100) {
    progress_count++;
   } else {
    completed_count++;
   }
});
   console.log('Progress count :',progress_count);
   console.log('Completed count :',completed_count);
}

并在HTML中使用progress_count和completed_count

答案 1 :(得分:1)

更改此行

count +=item.progress;

收件人

if (item.progress === 100) {count += 1;}

答案 2 :(得分:1)

尝试这样:

progressCount:number = 0;
completedCount:number = 0;


ngOnInit() {
this.array.forEach(item => {
  if (item.progress < 100) {
    this.progressCount ++;
  } else {
    this.completedCount ++;
  }
});
}

HTML:

<div>Progress : 2{{progressCount}}</div><div>completed : 2{{completedCount}}</div> 

答案 3 :(得分:0)

您可以使用underscore之类的库,其中countBy之类的函数可以满足您的要求。

在您的情况下:

_.countBy(array, (item) => item.progress === 100 ? 'completed' : 'progress');

结果将是:

{completed: 2, progress: 2}