首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript -通过id更新数组中的对象,并将其移动到第一个索引

Javascript -通过id更新数组中的对象,并将其移动到第一个索引
EN

Stack Overflow用户
提问于 2021-01-19 01:34:19
回答 2查看 48关注 0票数 0

我有这个数组:

代码语言:javascript
复制
const chats = [
   { id: "chat-1", msg: { text: "World", date: (a date) } },
   { id: "chat-2", msg: { text: "Hello", date: (a date) } },
];

在从我的数据库接收到更新之后,我收到了这个对象:

代码语言:javascript
复制
  // The second chat with update data
  { id: "chat-2", msg: { text: "Bye", date: (a date) } },

如何(使用ES6)替换原始聊天数组中的chat对象并将其移动到第一个索引?

现在,我正在做这件事,但我正在寻找一种最快的方法(较小的O)

代码语言:javascript
复制
// 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),
 ];
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-01-19 01:40:58

您可以执行以下操作:

代码语言:javascript
复制
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);

票数 1
EN

Stack Overflow用户

发布于 2021-01-19 01:46:25

您可以做一些类似于LRU cache工作方式的事情。您现在可以访问O(1)中的所有聊天

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65779382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档