0

I have an object list:

var myObj = {
   obj1: {name: "bob", employed: true},
   obj2: {name: "dave", employed: false},
   obj3: {name: "james", employed: true},
}

What is the most efficient/elegant way to iterate through the object list and count how many objects are equal employed: true. Is there a short way to write this? I was thinking of implementing it like below:

const countEmployed = () => {
    for (let key in myObj) {
      if (myObj .hasOwnProperty(key)) {
      }
    }
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Freddy.
  • 1,593
  • 2
  • 20
  • 32
  • Just [drop the `if (myObj .hasOwnProperty(key))` clause](https://stackoverflow.com/a/45014721/1048572) – Bergi Dec 14 '19 at 13:50

3 Answers3

1

You could use .reduce() on the Object.values() by using the boolean value of employed as a number to add to the total like so:

const myObj = {
   obj1: {name: "bob", employed: true},
   obj2: {name: "dave", employed: false},
   obj3: {name: "james", employed: true},
};

const sum = Object.values(myObj).reduce((t, {employed}) => t+employed, 0);
console.log(sum);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Usually efficient isn't equal to elegant, however if you are looking for a short and elegant method, you could use Array#filter:

const myObj = {
   obj1: {name: "bob", employed: true},
   obj2: {name: "dave", employed: false},
   obj3: {name: "james", employed: true},
};

const r = Object.values(myObj).filter(({ employed }) => employed).length;

console.log(r);

However, the most efficient way would be probably to use a for in loop and just increase a counter if the employed value is truthy.

kind user
  • 40,029
  • 7
  • 67
  • 77
0

Technically you can use Object.values() to get all the property values first. Then you can use Array.filter() to get only the necessary ones.

Based on that I would do the following:

const myObj = {
   obj1: {name: "bob", employed: true},
   obj2: {name: "dave", employed: false},
   obj3: {name: "james", employed: true},
}

const result = Object.values(myObj).filter(e => e.employed);
console.log('Count:', result.length);

Read further here:

  1. Array.prototype.filter()
  2. Object.values()

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59