Search code examples
javascriptobject-literal

Javascript Object Addition Assignment Operator


I am trying to use an addition assignment operator within a javascript object in order to add up the number of votes in a student election. Given the following:

var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" }
};

I am trying to preform a for/in loop in order to count and create a new object with the names of candidates and the number of votes they have:

var President = {};
for (var student in votes) {
  President[votes[student].president] += 1;
};

Which, as you probably already know, gives me all NaN values.

How do I get the key of the property to increase for each iteration?


Solution

  • The problem is you are not initializing the value. So the first time you encounter a name, you have President[votes[student].president] as undefined, so undefined + 1 will give you NaN, thereafter each addition will give you NaN since NaN + 1 is NaN

    var President = {}, president;
    for (var student in votes) {
        president = votes[student].president;
        if (!President[president]) {
            President[president] = 0;
        }
        President[president] += 1;
    };