skip to Main Content

Within my app, I have an object with the following structure

object = {"chatid1": {"messageId1": {message: "hello", id: 293839}, "messageId2": {message: "test", id: 2929292}}, "chatid2": {"messageId1": {message: 'hello', id: 292}}

I want to append a new message object (with its own key, e.g "messageId3") to a particular chatId. The result operation should mean that in the example above, "chatid1", should now look like the following:

"chatid1": {"messageId1": {message: "hello", id: 293839}, "messageId2": {message: "test", id: 2929292}, "messageId3": {message: "newMessage", id: 292121356}}

I tried to add the following code, however instead of appending an object, it replaced the value of whatever object[chatId] was.

Here is the code:

object[chatId] = {...object[chatId], messageToAdd}

messageToAdd has the following structure:

{"messageId3": {message: "newMessage", id: 2920222}}

How can I accomplish the task of appending to the object stored at the location chatId, instead of replacing it completely. Thanks.

2

Answers


  1. Here is probably what you are missing…

    object[chatId] = { ...object[chatId], ...messageToAdd };
    
    Login or Signup to reply.
  2. You haven’t spread the messageToAdd object, which led to replacing the value instead of appending the new message object. By using the spread operator on messageToAdd, you’re correctly merging the two objects.
    Something like:

    let object = {
      "chatid1": {
        "messageId1": {
          message: "hello",
          id: 293839
        },
        "messageId2": {
          message: "test",
          id: 2929292
        }
      },
      "chatid2": {
        "messageId1": {
          message: "hello",
          id: 292
        }
      }
    };
    
    const chatId = "chatid1";
    const messageToAdd = {
      "messageId3": {
        message: "newMessage",
        id: 2920222
      }
    };
    
    object[chatId] = { ...object[chatId],
      ...messageToAdd
    }; // This one
    
    console.log(object);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search