这是关于通过多个字段值对数组中的对象进行分组的另一个问题,但在我的情况下,我需要首先使用一个字段值,然后在每个组中使用第二个字段值。
首先,这是我的起始对象:
var typeData = [
0: {
details: {
circumference: 227.7655,
diameter: 72,
material:"SA-240 316",
thickness: 0.5,
width: 95
}
item: "Plate, 0.5000 in x 227.7655 in. x 95.0000 in",
label: "Cylinder #1",
type: "shell"
},
1: {
details: {
circumference: 227.7655,
diameter: 72,
material:"SA-240 316",
thickness: 0.5,
width: 95
}
item: "Plate, 0.5000 in x 227.7655 in. x 95.0000 in",
label: "Cylinder #2",
type: "shell"
},
2: {
details: {
circumference: 227.7655,
diameter: 72,
material:"SA-240 316",
thickness: 0.5,
width: 95
}
item: "Plate, 0.5000 in x 227.7655 in. x 95.0000 in",
label: "Cylinder #3",
type: "shell"
},
3: {
details: {
circumference: 227.7655,
diameter: 72,
material:"SA-516 70",
thickness: 0.5,
width: 95
}
item: "Plate, 0.5000 in x 227.7655 in. x 95.0000 in",
label: "Cylinder #4",
type: "shell"
},
4: {
details: {
circumference: 227.7655,
diameter: 72,
material:"SA-516 70",
thickness: 0.5,
width: 95
}
item: "Plate, 0.5000 in x 227.7655 in. x 95.0000 in",
label: "Cylinder #1",
type: "shell"
]
所以我需要做的是首先按item
字段值对对象进行分组,然后按details.material
字段值进行分组。使用上面的例子,我将有两个分组:
获得第一个分组并迭代完第一组非常简单:
_(typeData).groupBy('item').forEach(function(value, description) {
... do stuff here
}
我遇到问题的地方是试图进行第二次分组。我能够做到这一点:
_(typeData).groupBy('item').forEach(function(value, description) {
// Next, group by material, since there could be instances of the same item
// (such as a piece of plate) with an identical description but different material.
var tempMaterialData = _.groupBy(value, function(thing){
return thing.details.material;
});
}
现在我可以遍历tempMaterialData
。然而,这似乎有些愚蠢。有没有更好的方法可以将所有内容按照链接方式分组,所以我只需要一个_.forEach()?