具有嵌套属性的对象的投票计数器

时间:2014-07-28 02:03:30

标签: javascript

我一直致力于解决一个问题的解决方案,该问题要求在Javascript和每个投票办公室中统计选票,返回候选人名单和他们收到的选票

注意:我们被要求使用for..in loops

来回答这个问题

选票样本列表如下:

var votes = {
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
}

我的伪代码目前是这样的:

输入:投票

每次投票:

  1. 返回总统投票的名称
  2. 如果对象中已存在总统投票的密钥,则将值(计数)增加1
  3. 如果没有,请将密钥推入对象并将值增加1
  4. 重复其他办事处 输出:包含总统所有姓名和投票数的对象;彼此办公室的类似对象
  5. 我遇到问题的解决方案如下:

         var president = {}
         var vicePresident = {}
         var secretary = {}
         var treasurer = {}
    
    for (var personVoting in votes) { 
        ballots = votes[personVoting]
        for (var choice in ballots){
    //variable to capture the choice for president on the ballot
            var choice1=choice.hasOwnProperty("president")
            if president.hasOwnProperty(choice1)
                president.choice1.setItem(president.choice1.getItem+1)
            else 
                president.push(choice1: 1)
        }
    //Once the loop for president works, copy and make a similar loop for each other office
    }
    

    我可以使用一些帮助来解决这部分问题

0 个答案:

没有答案