簡體   English   中英

按地圖內數組項內的對象對對象數組進行排序

[英]Sort array of objects by objects inside of array items inside map

我想通過之日起就這些ChatListItems排序chat.messages.date

{
    userChats.map(chat => (
        <ChatLink key={chat._id} to={`/chats/${chat._id}`}>
            <ChatListItem
                partnerName={pickPartnerName(
                    userName,
                    chat.userName1,
                    chat.userName2
                )}
                userImgSrc={DefaultUserAvatar}
                lastMessage={chat.messages[chat.messages.length - 1].body}
                lastMessageDate={chat.messages[
                    chat.messages.length - 1
                ].date.slice(11, 16)}
            />
        </ChatLink>
    ));
}

db 對象如下所示:

const messageSchema = new mongoose.Schema({
    type: {
        type: String
    },
    body: {
        type: String
    },
    author: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    }
});

const chatSchema = new mongoose.Schema({
    userName1: String,
    userName2: String,
    messages: [messageSchema]
});

所以我想按這些消息的最后日期排序。 日期本身看起來像這樣: 2020-01-13 22:22:17.345Z

我將如何做到這一點?

提前致謝!

對不起,我的可怕問題標題

這是我實際嘗試實現的目標的視覺效果。 https://i.stack.imgur.com/zQkxl.png

要對您的 chat.messages 進行排序,您可以通過這種方式進行處理

chat.messages.sort((a,b)=>a.date.getTime()-b.date.getTime());

現在,它是由你改變得到你想要的順序a.date.getTime()-b.date.getTime()bdate.getTime()-a.date.getTime()

暫無
暫無

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

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