[英]Trying to wrap a reduce function in another function so as to make it more general
我的 object 看起來像這樣:
electionResults = {
constituency_1:{
party1:'200',
party2:'400'
...
},
constituency_2:{
party1:'100',
party2:'500'
...
},
...
}
我正在統計這樣的結果:
Object.values(electionResults).reduce((t, {party1}) => t + +party1, 0)
我希望能夠像這樣包裝它:
function partyTally(myParty){
return Object.values(electionResults).reduce((t, myParty) => t + +party1, 0)
}
但無法弄清楚如何將myParty
傳遞給減少回調 function。 我自己從 tsv 文件創建了 object,因此如果需要,可以輕松地重新配置它。
提前感謝您的幫助。
編輯
所需的 function 應為:
function partyTally(myParty){
return Object.values(electionResults).reduce((t, myParty) => t + +**myParty**, 0)
}
您可以通過使用Object.values
中的完整參數來完成此操作,而不是嘗試在回調中立即解構。
function partyTally(myParty){
return Object.values(electionResults).reduce((t, constituencyResults) => t + +constituencyResults[myParty], 0)
}
派對1是問題所在。 這里:
function partyTally(myParty){
return Object.values(electionResults).reduce((t, c) => t + Number(c[myParty]), 0)
}
例如,通過“party1”。
這是一次統計所有選區的所有政黨的方法:
electionResults = { "constituency_1": { "party1": "200", "party2": "400" }, "constituency_2": { "party1": "100", "party2": "500" } }; partiesTally = Object.values(electionResults).reduce((result, constituency) => { Object.keys(constituency).forEach(party => { if(result[party]==undefined) result[party]=0; result[party]+=(+constituency[party]); }); return result; },{}); console.log(partiesTally);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.