【发布时间】:2021-11-20 17:53:54
【问题描述】:
我正在寻找一种根据自定义要求将元素数组减少为对象的方法。
考虑这样的集合:
[
{
name: "David",
checkins: [
{
_id: "612e162d439cb04934d13f9e",
in_at: "2021-09-12T08:02:00.000Z",
out_at: "2021-09-12T09:03:00.000Z"
},
{
_id: "612e162d439cb04934d13f9f",
in_at: "2021-09-12T10:04:00.000Z",
out_at: "2021-09-12T11:05:00.000Z"
},
{
_id: "612e162d439cb04934d13f9g",
in_at: "2021-09-12T12:02:00.000Z",
out_at: "2021-09-12T14:03:00.000Z"
}
]
},
{
name: "Wilson",
checkins: [
{
_id: "612e162d439cb04934d13f9e",
in_at: "2021-09-12T08:02:00.000Z",
out_at: "2021-09-12T09:03:00.000Z"
},
{
_id: "612e162d439cb04934d13f9f",
in_at: "2021-09-12T11:04:00.000Z",
out_at: "2021-09-12T12:05:00.000Z"
},
{
_id: "612e162d439cb04934d13f9g",
in_at: "2021-09-12T13:02:00.000Z",
out_at: "2021-09-12T14:03:00.000Z"
}
]
}
]
现在我需要将 checkins 数组减少为单个对象并将其附加到新属性 checkin。只需要合并数组的第一个元素和数组的最后一个元素。如果只有一个元素,只需要使用自己,如果数组为空,则checkin必须为null。输出对象应该是:
{
_id: 1st_element_id,
in_at: 1st_element_in_at,
out_at: last_emenet_out_at
}
所以按照例子,预期的结果是:
[
{
name: "David",
checkin: {
_id: "612e162d439cb04934d13f9e",
in_at: "2021-09-12T08:02:00.000Z",
out_at: "2021-09-12T14:03:00.000Z"
}
},
{
name: "Wilson",
checkin: {
_id: "612e162d439cb04934d13f9e",
in_at: "2021-09-12T08:02:00.000Z",
out_at: "2021-09-12T14:03:00.000Z"
}
}
]
感谢任何帮助,谢谢!
【问题讨论】: