查找、更新元素并更改其在对象数组中的索引

Find, update an element and change its index in array of objects

我在这里想要实现的是一个聊天应用程序,其中最后一次对话(当前登录用户和目标用户之间)应该更新它的 lastMessage 并放在对话数组的第一个位置。

这是对话数组的简单版本:

const conversations = [
    { ... },
    {
        _id: 5,
        lastMessage: {
            sender: 1
            receiver: 2
            message: 'Hello World',
            conversation_id: 5
        }
    },
    { ... }
]

如果 id = 1 的用户向 id = 2 的用户发送消息,它应该更新 _id = 5 的对话并将其移动到对话数组的索引 0。

我目前所做的是将对话移动到数组的顶部,但我不知道如何更改它的 lastMessage。 (反应减速器)

conversations: [state.conversations.find(el => el._id === action.payload.conversation_id), ...state.conversations.filter(el => el._id !== action.payload.conversation_id)]

感谢任何能帮助我的人!

这样的东西能满足您的要求吗?

// find the first convo as you already do
const firstConversation = state.conversations
          .find(el => el._id === action.payload.conversation_id);

// this is the current `lastMessage`
const lastMessage = {...first.lastMessage};

// make changes to `lastMessage` here, or assign a completely new object as required
const firstConversationUpdated = {...firstConversation, lastMessage: lastMessage};

// update state below
conversations: [firstConversationUpdated, 
                ...state.conversations.filter(el => el._id !== action.payload.conversation_id)]