我有这个数组:
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)替换原始聊天数组中的chat对象并将其移动到第一个索引?
现在,我正在做这件事,但我正在寻找一种最快的方法(较小的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),
];发布于 2021-01-19 01:40:58
您可以执行以下操作:
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);
发布于 2021-01-19 01:46:25
您可以做一些类似于LRU cache工作方式的事情。您现在可以访问O(1)中的所有聊天
https://stackoverflow.com/questions/65779382
复制相似问题