簡體   English   中英

基於另一個數組中的對象的新數組

[英]New array based on objects inside another array

我有一系列約會對象:

let appointments = [
    { _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
    { _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"},
    { _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"},
    { _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"},
    { _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
]

我的目標是根據約會的天數創建一個新數組並將它們放在里面,如下所示:

{ days:
    { 2022-01-20: [
     { _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
     { _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"}
    ]},
    { 2022-01-21: [
     { _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"}
    ]},
     { 2022-01-22: [
     { _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"}
    ]},
     { 2022-01-23: []},
     { 2022-01-24: []},
     { 2022-01-25: [
      { _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
     ]},
}

“日期”的前 10 個字符可以成為新值(不包括重復值),並且在它們內部應該有適當的約會,因為它們在源中 - 僅按天組織。

我正在嘗試制作的另一個功能是在活動日期之間插入空白日期(第二個代碼中的示例)

謝謝你的幫助

 const appointments = [ { _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"}, { _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"}, { _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"}, { _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"}, { _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"} ]; const appointmentsByDate = appointments.reduce( (acc, appointment) => { // split the date string and store index 0 as date variable. const [date] = appointment.date.split('T'); return {...acc, // overwrite or add date key to the accumulator. // if the date key already exists, spread the existing value into the new value [date]: [...(acc[date] || []), appointment], }; }, {} // starting accumulator (acc) value ); console.log(appointmentsByDate);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM