Using Javascript, I want to push some values into an array, then push that array into an object, but I’m getting the error message Cannot read properties of undefined (reading 'push')
.
I looked at JavaScript: Push into an Array inside an Object? and I appear to be using the same syntax. What am I doing wrong?
//global vars
var arrPlayer = [];
var objPicked;
$(document).ready(function() {
arrPlayer = [{'PlayerID':3}, {'Num': '--'}, {'First': 'John'}, {'Last': 'Smith' }, {'Position': 'QB'}];
objPicked.push(arrPlayer); //throws error
});
3
Answers
Your
objPicked
is undefined.There are several things that you’re doing wrong.
First, you cannot "push into" an empty object. Object needs to be initialized or otherwise, it would be
undefined
. So, initialize your object first:Now,
push()
is a method ofArray
so even if you initialized it, there won’t be apush
method.If I understood correctly, what you’re trying to do is add an array to the object as a member and push into that array. So, you need to add it when initializing:
Now, you can indeed push into
objPicked.players
because it’s an array:But if you want to "push"
arrPlayer
, which is already an array, into the array, you should not usepush
because if you do, it’d create a 2-dimensional array, so for that, you need to useconcat()
, or simply an assignment if the original array is empty:Initialize your object like this
you need to add the array to your object under a key name, it can be almost anything you want. I recommend a name that will help you reconigze what kind of data you have in there, In this example will give the object a key named
players
If you want to access the array that was just stored only the you can use the key to do so.
Final code would look like this