我有数组结果,如果数组值相同,则创建新的数组列表
这是我的示例数组:
[
{
"dayName": 1,
"time": {
"availabilityId": 1,
"fromTime": "05:30:00",
"toTime": "10:00:00"
}
},
{
"dayName": 1,
"time": {
"availabilityId": 2,
"fromTime": "10:30:00",
"toTime": "06:00:00"
}
},
{
"dayName": 2,
"time": {
"availabilityId": 3,
"fromTime": "16:30:00",
"toTime": "22:00:00"
}
}
]
但是我想要这样的数组
[
{
"dayName": 1,
"time":[
{
"availabilityId": 1,
"fromTime": "05:30:00",
"toTime": "10:00:00"
},
{
"availabilityId": 2,
"fromTime": "10:30:00",
"toTime": "06:00:00"
}
]
},
{
"dayName": 2,
"time":[
{
"availabilityId": 3,
"fromTime": "16:30:00",
"toTime": "22:00:00"
}
]
}
]
因为前两个数组dayName
是相同的,所以我想创建类似数组的数组
这是我尝试过的代码
CubbersAvailability.findAll(
{
where:{
cubbersId:cubbersId,
userId:userId,
status:1
},
attributes:['availabilityId', 'dayName', 'fromTime', 'toTime']
}
).then(availabilityList =>{
let list = [];
availabilityList.forEach(result => {
list.push({
"dayName": result.dayName,
"time": {
"availabilityId": result.availabilityId,
"fromTime": result.fromTime,
"toTime": result.toTime
}
});
});
答案 0 :(得分:3)
您可以使用reduce()
将数组汇总为一个对象。使用Object.values
将对象转换为数组。
let availabilityList = [{"dayName":1,"time":{"availabilityId":1,"fromTime":"05:30:00","toTime":"10:00:00"}},{"dayName":1,"time":{"availabilityId":2,"fromTime":"10:30:00","toTime":"06:00:00"}},{"dayName":2,"time":{"availabilityId":3,"fromTime":"16:30:00","toTime":"22:00:00"}}]
let result = Object.values(availabilityList.reduce((c, {dayName,time}) => {
c[dayName] = c[dayName] || {dayName,time: []};
c[dayName].time.push(time);
return c;
}, {}));
console.log(result);
答案 1 :(得分:1)
CubbersAvailability.findAll(
{
where:{
cubbersId:cubbersId,
userId:userId,
status:1
},
attributes:['availabilityId', 'dayName', 'fromTime', 'toTime']
}
).then(availabilityList =>{
let list = [];
availabilityList.forEach(result => {
list.push({
"dayName": result.dayName,
"time": {
"availabilityId": result.availabilityId,
"fromTime": result.fromTime,
"toTime": result.toTime
}
});
});
let result = Object.values(list.reduce((c, {dayName,time}) => {
c[dayName] = c[dayName] || {dayName,time: []};
c[dayName].time.push(time);
return c;
}, {}));
res.status(200).send({status: 'success', resCode:200, data:result});
}).catch(error=>{
res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});
});
结果
{
"status": "success",
"resCode": 200,
"data": [
{
"dayName": 1,
"time": [
{
"availabilityId": 1,
"fromTime": "05:30:00",
"toTime": "10:00:00"
},
{
"availabilityId": 2,
"fromTime": "10:30:00",
"toTime": "06:00:00"
}
]
},
{
"dayName": 2,
"time": [
{
"availabilityId": 3,
"fromTime": "16:30:00",
"toTime": "22:00:00"
}
]
}
]
}