Javascript - append object to an existing key within an existing object

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.


  • Here is probably what you are missing...

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