我正在尝试使用Array.prototype.reduce()
对数据进行分组我按优先级分组,我的数据如下:
{ 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,因此我无法映射以获得所需的最终分组。
如何进一步提取减少的分组项目以获得最终结果?
答案 0 :(得分: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));