【问题标题】:Angular14 how to flatten array or reduce to get true valuesAngular14如何展平数组或减少以获得真实值
【发布时间】:2022-07-18 20:52:41
【问题描述】:

我有以下对象数组。我想获得属性为真的总计数。即在这种情况下,启用的总数为 5

let data = 
[
    {
        comment: true,
        attachment: true,
        actionPlan: true
    },
    {
        whenValue: '',
        comment: true,
        attachment: false,
        actionPlan: true
    }
]

我在下面尝试了一些方法,但没有成功。

const countObj = questionAttributes.questionMandatoryOptions.reduce((acc, curr) => {
    return {

//想要获取具有真值的属性 };

});

对于数组中的单个项目,我可以使用 followign 来实现:

const total =
            options[0];
        const totalelections = Object.values(
            total
        ).filter((v) => v).length;

谢谢

【问题讨论】:

    标签: typescript angular14


    【解决方案1】:
    let data = [{
        comment: true,
        attachment: true,
        actionPlan: true
      },
      {
        whenValue: '',
        comment: true,
        attachment: false,
        actionPlan: true
      }
    ];
    
    const countObj = data
      .map(x => Object.values(x)) // [[true, true, true], ["", true, false, true]]
      .flatMap(x => x) // [true, true, true, "", true, false, true]
      .filter(x => x === true) // [true, true, true, true, true]
      .length; // 5
    
    console.log(countObj); // 5
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2021-08-08
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2020-11-09
      • 2022-10-02
      • 2020-11-06
      相关资源
      最近更新 更多