【问题标题】:Angular 6 how to get count of the particular column based on same value from an array of objectAngular 6如何根据对象数组中的相同值获取特定列的计数
【发布时间】:2026-01-04 00:35:02
【问题描述】:

我有一个对象数组,并且我在 typescript 中使用 foreach 循环。根据我的数组,它包含 2 列,其值为 progress:100,其他列小于 100。所以在这里我需要计算列数有进度:100,例如这里应该是2。另外我需要获取所有列的进度值小于或不是100.for ex 这里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);
  }

}

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    改变这一行

    count +=item.progress;
    

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

    【讨论】:

      【解决方案2】:

      试试这样:

      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】:

        实际上,您正在将进度值添加到计数中。请试试这个..

        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

        【讨论】:

          【解决方案4】:

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

          在你的情况下:

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

          结果将是:

          {completed: 2, progress: 2}

          【讨论】: