2016-11-11 75 views
-1

我有一個問題,我似乎幾乎沒有線索得到答案。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}] 
} 
+0

您是否獲得在控制檯中的任何錯誤?如果是這樣,他們是什麼,在什麼方面? – Amy

+0

你是否意識到你正試圖調用'groupBy'中的'groupBy' * *? –

+0

你爲什麼要遞歸調用'groupBy'? – Timo

回答

3

你只需要到之前返回groups,不字符串化的對象。

function groupBy(array, cb) { 
 
    var groups = Object.create(null); 
 
    array.forEach(function (o) { 
 
     var key = cb(o); 
 
     groups[key] = groups[key] || []; 
 
     groups[key].push(o); 
 
    }); 
 
    return groups; 
 
} 
 

 

 
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; }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

什麼是**'.as-console-wrapper {max-height:100%!important; top:0; **用於? –

+5

它將控制檯擴展至100%高度,以閱讀更多結果。 –

+1

哦,這是聰明的妮娜,爲代碼片控制檯注入CSS。爲你拍手! +1 –