javascript - 按多个属性分组对象并合并数组属性
问题描述
在示例中,我使用 each 来遍历选择字段并创建一个数据数组,我需要对 2 个属性进行分组year
,并且cabin
该属性months
是一个我想合并的数组,事情是我遇到了一些麻烦想要的结果:
JSFIDDLE:http: //jsfiddle.net/tc39xu6b/2/
结果我得到:
[
{
"year": "2021",
"cabin": "1",
"months": [
"1",
"2"
]
},
{
"year": "2021",
"cabin": "1",
"months": [
"4"
]
},
{
"year": "2021",
"cabin": "2",
"months": [
"1",
"2"
]
},
{
"year": "2022",
"cabin": "1",
"months": [
"1",
"2"
]
},
{
"year": "2022",
"cabin": "1",
"months": [
"4"
]
},
{
"year": "2022",
"cabin": "2",
"months": [
"1",
"2"
]
}
]
这是我需要的结果:
{
"2021": [
{"cabin":1, "months": ["1", "2","4"]},
{"cabin":2, "months": ["1", "2"]}
],
"2022": [
{"cabin":1, "months": ["1", "2","4"]},
{"cabin":2, "months": ["1", "2"]}
]
}
解决方案
所以,你已经到了解决方案的中途了。
从你所拥有的我写了一个分组函数:
const addUnique=(arr1,arr2)=>{
arr2.forEach(item=>arr1.includes(item) || arr1.push(item))
return arr1;
}
const grouped= obj.reduce((groups,item)=>{
const yearItems=(groups[item.year]||[])
const cabinItem=yearItems.find(({cabin})=>cabin===item.cabin)
const newCabinItem=cabinItem||{cabin:item.cabin};
newCabinItem.months=addUnique(newCabinItem.months||[],item.months);
return {
...groups,
[item.year]: cabinItem
? yearItems.map(yearItem =>
yearItem.cabin === item.cabin
? newCabinItem
: yearItem)
: yearItems.concat([newCabinItem])
}
},{})
你可以看到它在这里工作:http: //jsfiddle.net/9huwkz5L/
推荐阅读
- php - Laravel - 使用 Eloquent 获取没有 id 的 belongsTo 关系
- ios - 在 ScrollView 中定义位置后更改设备方向时,Swift / SwitUI App 崩溃
- java - 如何创建放置 4 张桌子卡片的类/方法?
- eslint - 如何调试 eslint 规则?
- javascript - 在 Node.js 中迭代 CSV 文件中的单元格
- rust - 使用现有可变引用的嵌套方法调用
- spring-boot - 多个客户端的 Keycloak 单次注销问题
- python - Pygame Error getting list index out of range 但我不知道如何解决(我是新手)
- python - 解析亚马逊(Python)
- powershell - Powershell:从每个用户那里获取所有日历权限