0

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: {}
    } 

1 Answer 1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.