2017-04-27 15 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));