简体   繁体   中英

Counting values nested javaScript objects

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM