Search code examples
javascriptarraysobject

How can I push to an array that’s inside an object's element in JavaScript?


I have the following object:

var watchObject = {};

Here is the following code I'm trying to accomplish; if it exists in the object I want to append it and if it doesn't exist I want to create a new key/value pair. The key value pair looks like "23": [blah]. So if the "23"(data.room) exists in the object I will push another to it like "23":[blah,bleh].

//assume data.room is defined elsewhere and data.videoId is defined elsewhere

if (data.room in watchObject) {
    watchObject[data.room].push(data.videoId);
} else {
    watchObject[data.room] = data.videoId;
}

I tried the above, I thought it would work, but it keeps saying:

"TypeError: watchObject[data.room].push is not a function"

I've also tried assigning data.room into a variable without any luck:

if (data.room in watchObject) {
   let tempRoom = data.room;
   watchObject.tempRoom.push(data.videoId);
   //watchObject[data.room].push(data.videoId);
} else {
    watchObject[data.room] = data.videoId;
}

And I get this error:

"TypeError: Cannot read property 'push' of undefined"


Solution

  • It's because watchObject[data.room] is blah (i.e. videoId) rather than [blah] (i.e. array of videoIds] hence the error push is not a function because a string won't have a push method.

    You need this:

    if(watchObject[data.room] == null) {
      watchObject[data.room] = []
    }
    // now you can safely push to the array
    watchObject[data.room].push(data.videoId)