Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to count the number of occurrences in a nested JavaScript object and assign it to an object. I know I need a for in loop but I can't figure out how to count each time that a value occurs. Here is the object I need to count:

var emmys = {
  "Alex": { drama: "Bob", horror: "Devin", romCom: "Gail", thriller: "Kerry" },
  "Bob": { drama: "Mary", horror: "Hermann", romCom: "Fred", thriller: "Ivy" },
  "Cindy": { drama: "Cindy", horror: "Hermann", romCom: "Bob", thriller: "Bob" },
  "Devin": { drama: "Louise", horror: "John", romCom: "Bob", thriller: "Fred" },
  "Ernest": { drama: "Fred", horror: "Hermann", romCom: "Fred", thriller: "Ivy" },
  "Fred": { drama: "Louise", horror: "Alex", romCom: "Ivy", thriller: "Ivy" }
}

var showVote = {
  drama: {},
  horror: {},
  romCom: {},
  thriller: {}
}

I want to get back something like this:

var showVote = {
      drama: { Louise: 2}, //etc
      horror: {Hermann: 3},
      romCom: {},
      thriller: {}
    } 
share|improve this question

1 Answer 1

I am one of those guys that likes native functions:

var result = Object.keys(emmys).reduce(function(res,person){
     var movieName ="";
     Object.keys(emmys[person]).forEach( function(key){
         movieName = emmys[person][key];
         if (!res[key][movieName]){ res[key][movieName] = 0; }
         res[key][movieName] += 1;
     });
     return res;
 }, {drama: {},horror: {},romCom: {},thriller: {}});

I tried to use some descriptive names but I wasn't sure they were right ones :)

share|improve this answer
1  
+1 definitely more elegant than mine... –  PinnyM Jan 29 at 21:25
    
@PinnyM thanks a lot I appreciate that –  Dalorzo Jan 29 at 21:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.