Reputation: 610
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: {}
}
Upvotes: 0
Views: 879
Reputation: 20014
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 :)
Upvotes: 1