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
});
2 Answers 2
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:
var objPicked = {};
Now, push() is a method of Array so even if you initialized it, there won't be a push 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:
var objPicked = {
players: []
};
Now, you can indeed push into objPicked.players because it's an array:
const player1 = {...};
const player2 = {...};
objPicked.players.push(player1);
objPicked.players.push(player2);
But if you want to "push" arrPlayer, which is already an array, into the array, you should not use push because if you do, it'd create a 2-dimensional array, so instead, you need to use concat(), or simply an assignment if the original array is empty:
// option 1
objPicked.players = objPicked.players.concat(arrPlayer);
// option 2
objPicked.players = arrPlayer;
If you do need to push arrays into your array inside the object, you can:
const objPicked = {
players: [],
};
const arrPlayer1 = [{'PlayerID':3}, {'Num': '--'}, {'First': 'John'}, {'Last': 'Smith' }, {'Position': 'QB'}];
const arrPlayer2 = [{'PlayerID':4}, {'Num': '--'}, {'First': 'Jane'}, {'Last': 'Doe' }, {'Position': 'FW'}];
objPicked.players.push(arrPlayer1);
objPicked.players.push(arrPlayer2);
console.log(objPicked.players);
Comments
Your objPicked is undefined.
Additionally, object must contain a key value pair. So here, I've created a "data" key and assigned the arrPlayer list to it's value in the objPicked object.
var arrPlayer = [];
var objPicked = {}; // define variable
arrPlayer = [{ 'PlayerID': 3 }, { 'Num': '--' }, { 'First': 'John' }, { 'Last': 'Smith' }, { 'Position': 'QB' }];
objPicked.playerData = arrPlayer; // Assign arrPlayer to objPicked as a property
console.log(objPicked);
objPickedvariable is uninitialized nor is it an array.let objPicked = {};then if you want to add it to the object you need to assign your object a key name kinda likeobjPicked.players = arrPlayervar objPicked = { players: [] }and thenobjPicked.players.push(arrPlayer);.