1

I have to get the length of boolean value (if it is true) in just an object. Can anyone help me solve this?

var data = {
             mo: true, 
             tu: true, 
             we: true, 
             th: true, 
             fr: true, 
             sa: false, 
             su: false
           };
Pradeep
  • 11
  • 6

2 Answers2

3

Here are two ways to do it (modern & shorter vs. backwards-compatible & longer):

var data = {
             mo: true, 
             tu: true, 
             we: true, 
             th: true, 
             fr: true, 
             sa: false, 
             su: false
           };

const short = Object.values(data).filter((v) => v).length;

var long = 0;

for (var prop in data) {
  if (data.hasOwnProperty(prop) && data[prop]) {
    long++;
  }
}

console.log(short, long);

In the modern version, we take only the values in the object, filter out any that aren’t truthy, and take the length of the resulting array.

In the backwards-compatible version, we loop through the properties of the object, filter out any that aren’t its own properties or aren’t truthy, and increment the count.

Aankhen
  • 2,198
  • 11
  • 19
  • Woah! this one worked like a charm. **Thank you so much!** Sorry, I couldn't up-vote for your answer guys. I'm really grateful – Pradeep Jul 11 '18 at 07:27
-1

Here is a simple way to do it

function totalBoolean(data){
 booleanTotal = 0;
 for (key in data) 
 booleanTotal += data[key]
 return booleanTotal;
}

var total = totalBoolean(data)
Jeffin
  • 1,099
  • 12
  • 23