skip to Main Content

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


  1. Your objPicked is undefined.

    <!doctype html>
    <html>
    
    <head>
        <title>JS With JQuery</title>
        <script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
    </head>
    
    <body>
        <script>
    
            // Javascript start
    
            var arrPlayer = [];
            var objPicked = {}; // define variable
    
            $(document).ready(function () {
                arrPlayer = [{ 'PlayerID': 3 }, { 'Num': '--' }, { 'First': 'John' }, { 'Last': 'Smith' }, { 'Position': 'QB' }];
    
                objPicked["data"] = arrPlayer; // add a key value pair to the objPicked object
                console.log(objPicked);
            });
    
            // Javascript end
    
        </script>
    </body>
    Login or Signup to reply.
  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 for that, 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;
    
    Login or Signup to reply.
  3. Initialize your object like this

    let objPicked = {};
    

    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

    objPicked.players = arrPlayer; 
    

    If you want to access the array that was just stored only the you can use the key to do so.

    console.log(objPicked.players);
    

    Final code would look like this

    //global vars
    let arrPlayer = [];
    let objPicked = {};
    
    arrPlayer = [{'PlayerID':3}, {'Num': '--'}, {'First': 'John'}, {'Last': 'Smith' }, {'Position': 'QB'}];
    objPicked.players = arrPlayer; 
    
    console.log(objPicked)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search