gpt4 book ai didi

javascript - 如何映射和分组对象数组

转载 作者:行者123 更新时间:2023-11-30 11:05:53 25 4
gpt4 key购买 nike

我正在使用 Node.js、Express、Postgres 和 Sequelize 构建应用程序。

我收到的回复如下所示:

[
{
"id": 101,
"type": 0,
"bookings": [
{
"date": "2019-04-15T02:00:00.000Z"
}
]
},
{
"id": 102,
"type": 4,
"bookings": [
{
"date": "2019-04-17T02:00:00.000Z"
}
]
},
{
"id": 103,
"type": 0,
"bookings": [
{
"date": "2019-04-15T02:00:00.000Z"
}
]
},
{
"id": 104,
"type": 0,
"bookings": [
{
"date": "2019-04-17T02:00:00.000Z"
}
]
}
]

我想对同一天发生的所有事件进行分组。

我试过了

_.forEach(response, function(value) {
_.groupBy(value, value.bookings[0].date)
})

但它不起作用。

如何映射和分组数组?

最终我想要一个看起来像这样的对象(或数组):

{
2019-04-15: [
{ id: 101, type: 0 }, { id: 103, type: 0}
],
2019-04-17: [
{ id: 102, type: 4 }, { id: 104, type: 0}
]
}

最佳答案

您可以使用 reduce

let data = [{"id": 101,"type": 0,"bookings": [{"date": "2019-04-15T02:00:00.000Z"}]},{"id": 102,"type": 4,"bookings": [{"date": "2019-04-17T02:00:00.000Z"}]},{"id": 103,"type": 0,"bookings": [{"date": "2019-04-15T02:00:00.000Z"}]},{"id": 104,"type": 0,"bookings": [{"date": "2019-04-17T02:00:00.000Z"}]}]

let op = data.reduce((op,{bookings,...rest}) => {
let key = bookings[0].date.split('T',1)[0]
op[key] = op[key] || []
op[key].push(rest)
return op
},{})

console.log(op)

关于javascript - 如何映射和分组对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com