javascriptarraysobject

Declaring a Javascript Array containing Objects


Is there a way I can declare an object array like this [{}]?

So in the following Code:

 club = {};
 club.player_DB                 = [{}]; // Player Database;
        
 // club.player_DB[0] = {};
 club.player_DB[0].code         = 44;
 console.log(club.player_DB[0].code);
            
 // club.player_DB[1] = {};
 club.player_DB[1].code         = 21;
        
 console.log(club.player_DB[0].code+" "+club.player_DB[1].code);    

I have declared the club.playerDB with [{}], i.e an array that contains an object; Or do I have to declare the object on each array (commented out {} declaration) for each player.

Thanks.


Solution

  • What Pointy means in their comment is that you can do this:

    const club = {};
    club.player_DB = [{}]; // Declare an array containing an object.
    
    club.player_DB[0] = 42; // Then assign a number.
    
    console.log(club.player_DB);  // No trace of the object.

    However, as Ray Wallace explains, you cannot access a property of an undefined object, so you do need to allocate your array elements before adding any properties to them:

    const club = {player_DB: [{}]};
            
    club.player_DB[0].code = 44;  // The first element already exists.
    
    club.player_DB[1] = {code: 21};
    
    club.player_DB.push({code: 13});
            
    console.log(club.player_DB[0].code+" "+club.player_DB[1].code+" "+club.player_DB[2].code);

    Also note that I added the const keyword to the club object initialisation to avoid declaring it in the global scope.