I have the following array of object. I want to get total count where properties are true. i.e in this case total enabled is 5
let data =
[
{
comment: true,
attachment: true,
actionPlan: true
},
{
whenValue: '',
comment: true,
attachment: false,
actionPlan: true
}
]
I tried something below but it didnt worked.
const countObj = questionAttributes.questionMandatoryOptions.reduce((acc, curr) => {
return {
//want to get properties having true values
};
});
For single item in array i can achieve with followign:
const total =
options[0];
const totalelections = Object.values(
total
).filter((v) => v).length;
CodePudding user response:
You alresdy found the solution for a single element, so all you really need
to do is to iterate over every element in your data
and increase a counter with the result of
Object.values(item).filter((v) => v).length;
let data =
[
{
comment: true,
attachment: true,
actionPlan: true
},
{
whenValue: '',
comment: true,
attachment: false,
actionPlan: true
}
]
function countTrueProperties(a_data: any[]): number {
let count = 0;
for(const item of a_data){
count = Object.values(item).filter((v) => v).length;
}
return count;
}
console.log(countTrueProperties(data));