我需要幫助閱讀對象,按名稱分組並計算每次出現次數。JavaScript對象按屬性分組並推送到新對象
然後我需要將結果推送到另一個對象,我可以用handlebars迭代。
這裏是我的樣本對象:
var names = [
{ "name": "Person A" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person D" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person B" }
];
我已經發現了一些代碼將遍歷並從中總結出名字:
for(var i = 0; i < names.length; i++) {
if(!count[names[i].name]){
count[names[i].name] = 0;
}
count[names[i].name]++;
}
使我有以下幾點:
我需要將這些結果推送到一個新的對象f或把手來閱讀。所以,我需要的數據是這種格式:
這是我已經成功至今,我掙扎的數據推到我的反應對象作爲新項目。我不知道如何從count對象中檢索名稱和總數。
// Set up the data to be returned
var names = [
{ "name": "Person A" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person D" },
{ "name": "Person B" },
{ "name": "Person C" },
{ "name": "Person B" }
];
var count = {};
var response = { items:[] };
for(var i = 0; i < names.length; i++) {
if(!count[names[i].name]){
count[names[i].name] = 0;
}
count[names[i].name]++;
}
// Loop through the count object and populate response items
for(var key in count) {
response.items.push({
// How do i put the name and total here?
"name": "Person A",
"total": 12345
});
}
console.log(count);
console.log(response);
是的,這是完美的,太感謝你了 – Scott