简体   繁体   English

替换对象数组中的键值

[英]Replacing key value in array of objects

I'm working on a project that is a basic message app.我正在开发一个基本消息应用程序的项目。 basically i have created an array of objects that allows me to see pre built messages.基本上我已经创建了一个对象数组,允许我查看预先构建的消息。 Then i should be able to click a clear all button and clear all of the messages that are being displayed by looping through the array of objects.然后我应该能够单击清除所有按钮并清除通过循环遍历对象数组而显示的所有消息。 this is what i have so far in my messageData.js这是我目前在 messageData.js 中所拥有的

const messages = [
  {
    id: 'message1',
    message: 'Hello everyone! Welcome to hell',
    userId: 'user1',
  },
  {
    id: 'message2',
    message: 'Yall are weirdos!',
    userId: 'user3',
  },
  {
    id: 'message3',
    message: 'Hey! I think everyone is awesome!',
    userId: 'user2',
  },
  {
    id: 'message4',
    message: 'Thanks for saying that my friend.',
    userId: 'user4',
  },
  {
    id: 'message5',
    message: 'Hey buddy, what is up?',
    userId: 'user4',
  },
];

const getMessages = () => messages;

and what i want to do is basically on click allow the messages key value to be changed to an empty string onclick so that i get rid of the displayed messages without getting rid of the object so that i can later push new messages into these key values.我想要做的基本上是在单击时允许将messages键值更改为空字符串onclick以便我摆脱显示的消息而不摆脱对象,以便我以后可以push新消息push送到这些键值中.

I started to write this but i seem to be missing something..我开始写这个,但我似乎错过了一些东西..

const clearBtnFunction = () => {
  messages.splice(1, '');
};

i'll be calling the event listener on my main.js file so i'm not super worried about that part yet.我将在我的 main.js 文件上调用事件侦听器,所以我还不太担心那部分。 I just want to know the proper syntax for replacing the key value in the array if thats possible.如果可能的话,我只想知道替换数组中键值的正确语法。

const clearBtnFunction = () => {
  messages.foreach( ( message ) => {
      message.message = "";
  });
};

or with a for loop或使用 for 循环

const clearBtnFunction = () => {
  for( let i =0; i < messages.length; i++) {
      messages[i].message = "";
  }
};

Here is what i opted for.这是我选择的。 I placed this function, not in the messagesData.js but in the messages.js where i'm building the domstring我放置了这个函数,不是在 messagesData.js 中,而是在我构建 domstring 的 messages.js 中

const clearBtnFunction = (e) => {
 e.preventDefault();
 const messages = message.getMessages();
 messages.splice(0, messages.length);
 messageBuilder(messages);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM