我有一個問題,我似乎幾乎沒有線索得到答案。Javascript:按ID分組對象數組
我不知道我在做什麼錯。
代碼:
function groupBy(arr, cb) {
var groups = {};
arr.forEach(function(o) {
var group = JSON.stringify(cb(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function(group) {
return groups[group];
});
var result = groupBy(arr, function(i) {
return currentObject.branch.id;
})
}
var list = [{
id: "102",
name: "Alice"
}, {
id: "205",
name: "Bob",
title: "Dr."
}, {
id: "592",
name: "Clyde",
age: 32
}];
console.log(groupBy(list, function(i) {
return i.id;
}));
它應該返回什麼:
{
"102": [{id: "102", name: "Alice"}],
"205": [{id: "205", name: "Bob", title: "Dr."}],
"592": [{id: "592", name: "Clyde", age: 32}]
}
您是否獲得在控制檯中的任何錯誤?如果是這樣,他們是什麼,在什麼方面? – Amy
你是否意識到你正試圖調用'groupBy'中的'groupBy' * *? –
你爲什麼要遞歸調用'groupBy'? – Timo