【发布时间】:2020-02-09 18:26:29
【问题描述】:
我想按多个字段对我的数据进行分组。所以,我添加了数据和预期结果。
const skus = [
{
id: 1,
customAttributes: {
Color: 'Red',
Size: 'S',
Season: 2019
}
},
{
id: 2,
customAttributes: {
Color: 'Red',
Size: 'S',
Season: 2020
}
},
{
id: 3,
customAttributes: {
Color: 'Red',
Size: 'M',
Season: 2019
}
},
{
id: 4,
customAttributes: {
Color: 'Red',
Size: 'M',
Season: 2020
}
},
{
id: 5,
customAttributes: {
Color: 'Red',
Size: 'L',
Season: 2019
}
},
{
id: 6,
customAttributes: {
Color: 'Red',
Size: 'L',
Season: 2020
}
},
{
id: 7,
customAttributes: {
Color: 'Green',
Size: 'S',
Season: 2019
}
},
{
id: 8,
customAttributes: {
Color: 'Green',
Size: 'S',
Season: 2020
}
},
{
id: 9,
customAttributes: {
Color: 'Green',
Size: 'M',
Season: 2019
}
},
{
id: 10,
customAttributes: {
Color: 'Green',
Size: 'M',
Season: 2020
}
},
{
id: 11,
customAttributes: {
Color: 'Green',
Size: 'L',
Season: 2019
}
},
{
id: 12,
customAttributes: {
Color: 'Green',
Size: 'L',
Season: 2020
}
}
];
console.log( // groupBy is working by 1 parameter, but I don't know to make it multiple parameter
_.chain(skus)
.map(sku => sku.customAttributes)
.groupBy('Color')
.map((value, key) => ({ title: key, skus: value }))
.value()
);
// Just like: groupBy('Color', 'Size')
我想通过多个参数对这些 sku 进行分组,就像使用 lodash 的颜色和大小一样。
通过 1 个参数,它运行良好。但是当多个参数时,我就无法正确了。
预期结果是:
[
{
title: 'Red / S', // Color / Size
skus: [
{
id: 1,
customAttributes: {
Color: 'Red',
Size: 'S',
Season: 2019
}
},
{
id: 2,
customAttributes: {
Color: 'Red',
Size: 'S',
Season: 2020
}
}
]
},
{
title: 'Red / M', // Color / Size
skus: [
{
id: 3,
customAttributes: {
Color: 'Red',
Size: 'M',
Season: 2019
}
},
{
id: 4,
customAttributes: {
Color: 'Red',
Size: 'M',
Season: 2020
}
}
]
},
....
]
谢谢。
【问题讨论】:
标签: javascript angular typescript lodash