鑑於以下對象的數組:如何按日期對數組中的項目進行分組?
[
{
"notes": "Game was played",
"time": "2017-10-04T20:24:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "10",
"game_id": 1,
},
{
"notes": "Game was played",
"time": "2017-10-04T12:35:30+00:00",
"sport": "lacrosse",
"owner": "steve",
"players": "6",
"game_id": 2,
},
{
"notes": "Game was played",
"time": "2017-10-14T20:32:30+00:00",
"sport": "hockey",
"owner": "steve",
"players": "4",
"game_id": 3,
},
{
"notes": "Game was played",
"time": "2017-10-04T10:12:30+00:00",
"sport": "hockey",
"owner": "henry",
"players": "10",
"game_id": 4,
},
{
"notes": "Game was played",
"time": "2017-10-14T20:34:30+00:00",
"sport": "soccer",
"owner": "john",
"players": "12",
"game_id": 5,
}
]
我想創建一個新的陣列,這將創建一個對象,每個日期(如鑰匙)和任何遊戲在遊戲上市當日播放(另一鍵)在同一個對象中。
新的數組應該是這樣的:
[
{
date:'date string',
games:[array of games played on the date]
},
{
date: 'other date',
games:[games under the other date]
}
]...
這裏是我做了什麼:
let t = this.state.data; (data above)
let list = [];
for (let i = 0; i < t.length; i++) {
let dates = t[i].time.slice(0,10);
if (!list[dates]) {
list[dates] = [];
}
list[dates].push(t[i]);
}
我的版本返回與日期爲值的數組,然後裏面的那些的遊戲列出,但我想列出它們在不同的鍵相同的對象。
任何幫助或指導將不勝感激。
你嘗試過這麼遠嗎?這裏的解決方案非常簡單。 –
嗨斯賓塞,我不確定如何在評論中發佈代碼,但我創建了一個空數組,並運行了for循環來遍歷第一個信息。我剪切原始日期以獲取(yyyy-mm-dd)格式,然後創建另一個for循環來檢查當前空數組中是否存在該日期,如果沒有,我將爲此創建一個新的密鑰日期,然後將任何遊戲傳入遊戲密鑰。起初,我得到一個無限循環,我的記憶崩潰了,然後我一直覆蓋我以前的對象。 – Blake
您不想在評論中發佈代碼,而是將其作爲編輯添加到問題中。 –