[英]Arrange Chat Messages By Date
我正在使用 Vue,但這是一個通用的 javascript 問題。 我調用 api 來獲取聊天 UI 的貓消息。 初始調用返回一個對象數組,其中每個對象都是一個聊天消息對象,如下所示。
data: [
0: {id: 1, created_at: "2022-05-20T15:12:40.000000Z", updated_at: "2022-05-20T17:18:03.000000Z",…}
1: {id: 2, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
2: {id: 3, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
3: {id: 4, created_at: "2022-05-20T15:12:41.000000Z", updated_at: "2022-05-20T17:18:04.000000Z",…}
]
我最初想格式化消息,以便他們可以在聊天窗口中按日期分組。 這是我用來分組的代碼
This is a computed property in vue
const formattedChats = computed(() => {
let dateFormattedMessages = messages.value.map(message => {
return {...message, updated_at: new Date(message.updated_at).toDateString(), created_at: new Date(message.created_at).toDateString()}
})
return dateFormattedMessages.reduce((total, currentValue) => {
total[currentValue.updated_at] = total[currentValue.updated_at] || [];
total[currentValue.updated_at].push(currentValue);
return total;
}, Object.create(null));
})
上面將首先將每個聊天對象將它們的updated_at
和created_at
轉換為日期字符串,然后使用 updated_at 對數組進行分組。 結果如下:
formattedChats = {
Fri Jun 24 2022: [
{...}, {...
]
Fri May 20 2022:[
{...}, {...
]
Mon Jun 27 2022:Array[
{...}, {...
]
Sat May 21 2022:Array[
{...}, {...
]
Tue Jun 28 2022:Array[
{...}, {...
]
}
如果您注意到,我面臨的問題是日期沒有按任何順序排列。 像這樣將它呈現到 UI 是沒有意義的,因為生成的聊天不是按日期排列的。 這就是 UI 的外觀
您需要使用數組(或地圖)來保持排序。 我會使用一個數組數組。 首先,您需要按日期對數據進行排序(我使用了updated_at
,我在數據數組中使用了 Date 類型)。 然后遍歷排序后的數組。 請參閱下面的片段。
const data = [{ id: 1, updated_at: new Date("2022-05-21T15:12:40.000000Z"), created_at: "2022-05-20T17:18:03.000000Z" }, { id: 2, updated_at: new Date("2022-05-20T15:12:41.000000Z"), created_at: "2022-05-20T17:18:04.000000Z" }, { id: 3, updated_at: new Date("2022-05-23T15:12:41.000000Z"), created_at: "2022-05-20T17:18:04.000000Z" }, { id: 4, updated_at: new Date("2022-05-21T15:12:41.000000Z"), created_at: "2022-05-20T17:18:04.000000Z" }, ] const sortedData = data.sort( (a, b) => Number(a.updated_at) - Number(b.updated_at), ); let currentDay = sortedData[0].updated_at; const stillCurrentDay = (dayOfMessage) => { return dayOfMessage.getFullYear() === currentDay.getFullYear() && dayOfMessage.getMonth() === currentDay.getMonth() && dayOfMessage.getDate() === currentDay.getDate() } let dayMessageArray = []; const fullMessageArray = []; const createMessagesArray = (messages) => { const newDay = {}; newDay[currentDay.toISOString().split('T')[0]] = messages; fullMessageArray.push(newDay); } sortedData.forEach(message => { if (!stillCurrentDay(message.updated_at)) { createMessagesArray(dayMessageArray); currentDay = message.updated_at; dayMessageArray = []; } dayMessageArray.push(message); }); createMessagesArray(dayMessageArray); console.log(fullMessageArray);
希望這可以幫助。 也許有更簡單的方法,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.