susu watari
susu watari

Reputation: 207

Count value in js object

I have an object of who are coming to the event

{ "Ann": true, "Billy": false, "Cat": false, "David": true }

How can I count the number of people is attending?

object.values.length to get the total number of people

Upvotes: 0

Views: 1871

Answers (5)

Code Maniac
Code Maniac

Reputation: 37755

You can use Object.values and reduce

Here the idea is

  • First get all the values from object.
  • Using reduce we sum up values.

let obj = { "Ann": true, "Billy": false, "Cat": false, "David": true }

let count = Object.values(obj).reduce((op,inp) => op + inp , 0)

console.log(count)

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816312

object.values.length to get the total number of people

Filter out false values:

const obj = {"Ann": true, "Billy": false, "Cat": false,"David": true};
console.log(
  Object.values(obj).filter(Boolean).length
);

If you want to get the names of people who are attending you can do something like this:

const obj = {"Ann": true, "Billy": false, "Cat": false,"David": true};

const attendees = Object.entries(obj)
  .filter(entry => entry[1])
  .map(entry => entry[0]);

console.log(attendees);
console.log(attendees.length);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

You could count the boolean value who is coerced to a number.

var object = { Ann: true, Billy: false, Cat: false, David: true },
    count = Object.values(object).reduce((a, b) => a + b, 0);

console.log(count);

Upvotes: 0

GifCo
GifCo

Reputation: 1363

You can do it many ways. Here is one with filter...

let obj = { "Ann": true, "Billy": false, "Cat": false, "David": true }   
Object.values(obj).filter( person => person === true).length

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074038

In modern environments, you can use a for-of loop on the array returned by Object.values:

let sum = 0;
for (const flag of Object.values(yourObject)) {
    if (flag) {
        ++sum;
    }
}

const yourObject = { "Ann": true, "Billy": false, "Cat": false, "David": true };
let sum = 0;
for (const flag of Object.values(yourObject)) {
    if (flag) {
        ++sum;
    }
}
console.log(sum);

or reduce on it:

const sum = Object.values(yourObject).reduce((sum, flag) => sum + (flag ? 1 : 0), 0);

const yourObject = { "Ann": true, "Billy": false, "Cat": false, "David": true };
const sum = Object.values(yourObject).reduce((sum, flag) => sum + (flag ? 1 : 0), 0);
console.log(sum);

In older environments, you can use for-in:

var sum = 0;
for (var key in yourObject) {
    if (yourObject[key]) {
        ++sum;
    }
}

var yourObject = { "Ann": true, "Billy": false, "Cat": false, "David": true };
var sum = 0;
for (var key in yourObject) {
    if (yourObject[key]) {
        ++sum;
    }
}
console.log(sum);

Upvotes: 0

Related Questions