js实现json数组根据相同字段,合并出新的数据?

把相同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,

},

],

},

]


回答:

    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)//格式化好的数据

以上是 js实现json数组根据相同字段,合并出新的数据? 的全部内容, 来源链接: utcz.com/p/933026.html

回到顶部