数组转换问题?
我有下面的形式的数组
[{
id: 1,
name: 1,
port: 1,
unit: 2
}, {
id: 2,
name: 2,
port: 3,
unit: 4
}]
我想根据id和name对其进行分组,得到下面形式的数组,代码要如何编写?
[{
id: 1,
name: 1,
ports: [
{
port: 1, unit: 2
}
]
},{
id: 2,
name: 2,
ports: [
{
port: 3, unit: 4
}
]
}]
回复
1个回答

test
2024-06-30
let arr = [{
id: 1,
name: 1,
port: 1,
unit: 2
}, {
id: 2,
name: 2,
port: 3,
unit: 4
}]
let res = [], obj = {}
arr.forEach(item => {
let key = item.id + '-' + item.name
let target = {port: item.port, unit: item.unit}
if(!obj[key]){
res.push(obj[key] = {
id: item.id,
name: item.name,
ports: [target]
})
}else{
obj[key].ports.push(target)
}
})
console.log(res)
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容