我正在尝试计算嵌套JavaScript对象中出现的次数并将其分配给对象。我知道我需要一个for循环但我无法弄清楚每次出现一个值时如何计算。这是我需要计算的对象:
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: {}
}
我希望得到这样的东西:
var showVote = {
drama: { Louise: 2}, //etc
horror: {Hermann: 3},
romCom: {},
thriller: {}
}
答案 0 :(得分:1)
我是那些喜欢原生功能的人之一:
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: {}});
我尝试使用一些描述性名称,但我不确定它们是否正确:)