2017-04-27 14 views
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,因此我無法映射以獲得我想要的最終分組。

如何進一步提取我縮小的分組項目以實現最終結果?

+1

是什麼樣子,如果你有在給定'priorityId'多個'type'值? – apsillers

+0

對於同一個'type',可能會有更多'priorityId'嗎? –

+0

「*這些項顯示爲數組*」 - 不,它是一個對象。只需用'for ... in'來迭代它,並修復每個屬性值 – Bergi

回答

1

假設對於每個priorityId,只有一個type

function group(arr) { 
 
    return arr.reduce(function(acc, o) { 
 
     if(acc[o.priorityId])          // if we already encountered this priorityId before... 
 
      acc[o.priorityId].colors.push(o.color);     // then just add this object's color to the array colors of this priorityId objects 
 
     else              // otherwise (if we haven't encounter it yet)... 
 
      acc[o.priorityId] = {type: o.type, colors: [o.color]}; // then create an object for it that has its type set to this object's type and its colors array containing (initially) this object's color 
 
     return acc; 
 
    }, {}); 
 
} 
 

 

 
var data = [ 
 
    { 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" } 
 
]; 
 

 
console.log(group(data));