1
我使用Array.prototype.reduce()試圖組數據如何進一步降低Array.prototype.reduce()物品進入新亞集團
我被priorityId分組和我的數據如下:
{ priorityId: 100, type: train color: black }
{ priorityId: 50, type: car, color: orange }
{ priorityId: 25, type: bike, color: yellow }
{ priorityId: 50, type: car, color: grey }
{ priorityId: 25 type: bike, color: white }
{ priorityId: 25, type: bike, color: green }
我也跟着解決方案張貼在這裏和編組運行完美: What is the most efficient method to groupby on a javascript array of objects?
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
我的分組現在看起來像下面
個groupedItems:
25:
{ priorityId: 25 type: bike, color: yellow }
{ priorityId: 25, type: bike, color: white }
{ priorityId: 25, type: bike, color: green}
50:
{ priorityId: 50, type: car, color: orange }
{ priorityId: 50, type: car, color: grey }
100:
{ priorityId: 100, type: train, color: black }
我最終想組我的數據是這樣的:
25: {
type: bike
colors: [yellow, white, green]
},
50:{
type: car
colors:[ orange, grey]
},
100:{
type: train
colors: [black]
}
我遇到的問題是我無法從我的縮小分組的項目迭代我的分組的項目。 這些項目顯示爲一個數組,但是長度爲0,因此我無法映射以獲得我想要的最終分組。
如何進一步提取我縮小的分組項目以實現最終結果?
是什麼樣子,如果你有在給定'priorityId'多個'type'值? – apsillers
對於同一個'type',可能會有更多'priorityId'嗎? –
「*這些項顯示爲數組*」 - 不,它是一個對象。只需用'for ... in'來迭代它,並修復每個屬性值 – Bergi