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 assinging data.room into a variable with no 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 get this error:
"TypeError: Cannot read property ‘push’ of undefined"
4
Answers
It’s because
watchObject[data.room]
isundefined
.You need this:
The issue is that once you create the entry via this code…
it is not an array so the next time you try this code…
it will fail with the error you see.
A simple option here is to lazily create an array before pushing
See Nullish coalescing assignment (??=)
You almost done. But you have some mistake.
Try this.
let watchObject = {};
// Init
data
This will works well.
To push an element to an array that is inside an object in JavaScript, you can access the object, then access the array property using dot notation or square brackets, and finally use the push() method to add the element. Here’s an example:
This code snippet demonstrates accessing the myArray property of myObject and pushing the element "newElement" to it.