js实现数组根据相同字段,合并出新的数据?
把相同batch合并,并生成对应的positionList 数组原始数组:
const list = [
{
positionId: '1001',
positionName: 'B-b-b-101',
batch: '1',
num: 5,
},
{
positionId: '1002',
positionName: 'B-b-b-102',
batch: '2',
num: 3,
},
{
positionId: '1004',
positionName: 'B-b-b-104',
batch: '1',
num: 1,
},
{
positionId: '1004',
positionName: 'B-b-b-105',
batch: '2',
num: 3,
},
]
期望数组:
const list = [
{
positionId: '1001',
positionName: 'B-b-b-101',
batch: '1',
num: 5,
positionList: [
{
positionId: '1001',
positionName: 'B-b-b-101',
num: 5,
},
{
positionId: '1004',
positionName: 'B-b-b-104',
num: 1,
},
],
},
{
positionId: '1002',
positionName: 'B-b-b-102',
batch: '2',
num: 3,
positionList: [
{
positionId: '1002',
positionName: 'B-b-b-102',
num: 2,
},
],
},
{
positionId: '1005',
positionName: 'B-b-b-105',
batch: '2',
num: 3,
positionList: [
{
positionId: '1005',
positionName: 'B-b-b-105',
num: 3,
},
],
},
]
回复
1个回答

test
2024-07-17
const list = [
{
positionId: '1001',
positionName: 'B-b-b-101',
batch: '1',
num: 5,
},
{
positionId: '1002',
positionName: 'B-b-b-102',
batch: '2',
num: 3,
},
{
positionId: '1004',
positionName: 'B-b-b-104',
batch: '1',
num: 1,
},
{
positionId: '1004',
positionName: 'B-b-b-105',
batch: '2',
num: 3,
},
]
let obj ={}
let newList = list.reduce((item, next) => {
obj[next.batch] ? '' : obj[next.batch] = true && item.push(next)
return item
}, []).map(m=>{
m.positionList = JSON.parse(JSON.stringify(list.filter(f => f.batch == m.batch)))
return m
})
console.log(newList)//格式化好的数据
回复

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