js如何合并对象数组中的某些项?

Twisted
  • 354

源数据:

data: [
{
    parkId: 1,
    scheduleId: 1,
    hasStock: false
},
{
    parkId: 1,
    scheduleId: 2,
    hasStock: false
},
{
    parkId: 1,
    scheduleId: 3,
    hasStock: false
},
{
    parkId: 2,
    scheduleId: 1,
    hasStock: false
},
{
    parkId: 2,
    scheduleId: 2,
    hasStock: false
},
{
    parkId: 2,
    scheduleId: 3,
    hasStock: false
}
]

期望是将parkId相同的项合并组成以下格式:

[
    {
        parkId: 1,
        date: [
            {
                scheduleId: 1,
                hasStock: false
            },
            {
                scheduleId: 2,
                hasStock: false
            },
            {
                scheduleId: 3,
                hasStock: false
            }
        ]
    },
    {
        parkId: 2,
        date: [
            {
                scheduleId: 1,
                hasStock: false
            },
            {
                scheduleId: 2,
                hasStock: false
            },
            {
                scheduleId: 3,
                hasStock: false
            }
        ]
    }
]

各位大佬有没有什么比较优雅的方式

回复
阅读 1.2k
3 个回答
let aux={}
let result=[]
data.forEach(obj=>{
  let {parkId,...restProps}=obj
  if(!aux[parkId]) aux[parkId]={ parkId, data:[] }
  aux[parkId].data.push({...restProps})
})
for(let key in aux){
  result.push(aux[key])
}

使用aux作为一个储存中介,可以支持乱序

data.map(d => d.parkId).filter((v, idx, arr) => arr.indexOf(v) === idx).map(parkId => {
  let d = {parkId, data: []}
  d.data = data.filter(item => item.parkId === parkId).map(item => {
    return {
        scheduleId: item.scheduleId,
        hasStock: item.hasStock
    }
  })
  return d
})

不过谈不上优雅。

let uniqueObj = {};
let result = data.map( item => {
    return {
        parkId: item.parkId,
        data: data.filter( childItem => childItem.parkId === item.parkId)
    }
}).reduce( (array, item) => {
    if(!uniqueObj[`parkId${item.parkId}`]) {
        array.push(item);
        uniqueObj[`parkId${item.parkId}`] = true;
    }
    return array;
}, []);
uniqueObj = null; //解除内存占用
console.log(result);
你知道吗?

宣传栏