2

I am using an object to store state and the object looks like this:

{
  "CPC": 0,
  "NDP": 0,
  "LPC": 0,
  "GPC": 1,
  "PPC": 2
} 

Where all the key values are an enumerator of a generic type <T>.

Suppose I can call this object, as such:

console.log(this.optionVotes()); 
// Produces:
{  "CPC": 0,   "NDP": 0,   "LPC": 0,   "GPC": 1,   "PPC": 2 } 

What is the best way I can get the of value 3 from this?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Anon
  • 2,267
  • 3
  • 34
  • 51

2 Answers2

4

You can use Object.keys() and Array.prototype.reduce()

Code:

const data = {  "CPC": 0,   "NDP": 0,   "LPC": 0,   "GPC": 1,   "PPC": 2 };
const result = Object
  .keys(data)
  .reduce((a, key) => a + data[key], 0);

console.log(result);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • I recommend also using the `index`, `array` arguments of the [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) function. That makes refactoring it easier if you want to define it as an external function. – k0pernikus Oct 17 '19 at 10:32
2

Objec.value(obj) will return an array of values inside keys and reduce does the rest of adding each value in var c counter inside reduce's callback.

var foo =  {  "CPC": 0,   "NDP": 0,   "LPC": 0,   "GPC": 1,   "PPC": 2 } 
console.log(Object.values(foo).reduce((a, c) => a + c, 0))
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38