【问题标题】:How to count a boolean value from a map如何从地图中计算布尔值
【发布时间】:2020-07-21 15:59:48
【问题描述】:

使用的框架是 Angular 8

我有一个名为 teams 的数组,我可以使用 teams.length 来获取其中的长度。 现在teams 为每个计数都有一个名为teamInfo 的映射。这个 teamInfo 映射再次有一个布尔值 isClosed 可以通过 teams.teamInfo.isClosed 访问每个计数,当它被 jsoning 到 ngforloop 时,这是

*ngFor=" let teamID of JSObject.keys(teams); trackBy: trackByFn

<app-team-card
[team]="teams[teamID]"
[isClosed]="teams[teamID].teamInfo.isClosed">
</app-team-card>

我的目标是获取所有拥有isClosed =true.的地图的数量我的尝试是

getClosedTeams(teams) {
         let closedTeams = teams.teamInfo.filter((isClosed) => {
             return isClosed.select == true;
        });
        console.log(closedTeams.length);
    }

【问题讨论】:

  • 您面临的问题是什么?还将比较 isClosed.select == true 更改为 isClosed.select === true
  • 你也说teamInfo是map,map没有filter属性。您将 filter 与 array 一起使用。如果你能提供问题中的数据就更好了

标签: javascript arrays angular typescript


【解决方案1】:

您可以使用.reduce 执行以下操作:

const team01 = new Map();
team01.set('name', 'team-01');
team01.set('isClosed', false);

const team02 = new Map();
team02.set('name', 'team-02');
team02.set('isClosed', true);

const team03 = new Map();
team03.set('name', 'team-01');
team03.set('isClosed', true);

const teams = [team01, team02, team03];

function getClosedTeamsCount (teams) {
  return teams.reduce((acc, teamInfo) => {
    return Number(teamInfo.get('isClosed')) + acc;
  }, 0)
}

console.log(getClosedTeamsCount(teams));

【讨论】:

  • teams 是一个数组,然后它有 teamInfo 作为 map ,它有 isClosed 属性。这行得通吗?
  • 就团队是一个数组而言,它应该可以工作。您只需要访问数组中每个元素的 isClosed 属性。
  • 我明白,但属性 isClosed 是团队数组的一部分还是团队数组内的 teamInfo 映射?检查问题一次I have an array called teams of which i can get the length by using teams.length . Now teams has a map called teamInfo for each count. This teamInfo map has again a boolean value isClosed
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2017-07-30
  • 2016-05-31
  • 2020-09-09
  • 1970-01-01
  • 2018-09-13
相关资源
最近更新 更多