我有这个数组:
const chats = [
{ id: "chat-1", msg: { text: "World", date: (a date) } },
{ id: "chat-2", msg: { text: "Hello", date: (a date) } },
];
从数据库接收更新后,我收到此对象:
// The second chat with update data
{ id: "chat-2", msg: { text: "Bye", date: (a date) } },
如何(使用ES6)替换原始聊天数组中的聊天对象并将其移至第一个索引?
目前,我正在这样做,但是我正在寻找最快的方法(较小的O)
// Get the modified chat
const modifiedChat = response.data;
// Search the modified chat in the chats array by id
const chatIndex = chats.findIndex(
(chat) => chat.id === modifiedChat.id
);
// Finally, using spread syntax, add the updated chat to the head of our current chats array
chats = [
modifiedChat,
...chats.slice(0, chatIndex),
...chats.slice(chatIndex + 1),
];
您可以执行以下操作,
const chats = [
{ id: "chat-1", msg: { text: "World", date: '' } },
{ id: "chat-2", msg: { text: "Hello", date: '' } },
];
const modifiedChat = { id: "chat-2", msg: { text: "Bye", date: '' } };
const newChats = [modifiedChat, ...chats.filter(item => item.id !== modifiedChat.id)];
console.log(newChats);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句