0

I am trying to create an object that looks like this:

{
   Player1: [
      {cardName: "test", 
       balanceNum: null,  
       ability:""}
   ],
   Player2: [
      {cardName: "test", 
       balanceNum: null,  
       ability:""}
   ],
   .
   .
   .
}

At the moment I am currently using this attempt to loop through and create this dynamically. Player gets update through the loop and I want each new entry to start with player1 and continue to playerN.

var playersInfoList = [];
var playerStatus = [];
var player = "";
var index = 1;
for (i = 0; i < playerCount; i++) {
   player = "player" + index++;
   playerStatus.push({
      cardName: "", 
      balanceNum: null,  
      ability:""
   });
   playersInfoList.push({
      [player]: playerStatus
   });
}
Ivar
  • 6,138
  • 12
  • 49
  • 61

3 Answers3

0

There's no need for the second array.


Also, key-value array's are somehow different in JS. Please check Best way to store a key=>value array in JavaScript?.


This should get you the desired output;

const playerCount = 15;   // example
var playersInfoList = {}; // Result

for (i = 0; i < playerCount; i++) {

   // Create key as 'player' + i
   var key = "player" + i;
   
   // Add new object
   playersInfoList[key] = {
      cardName: "", 
      balanceNum: null,  
      ability:""
   };
}
console.log(playersInfoList); // Show result
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Thank you so much this is what I needed! I just added a + 1 to the i in the var key so that is starts with player1 instead of player0 – Joshua Parker Oct 26 '20 at 16:44
0

Other solution is using Array.prototype.reduce():

playerCount = 5;
const result = Array.from(Array(playerCount)).reduce( (current, _, i) => {
  current[`player${i+1}`] =  [{
    cardName: "", 
    balanceNum: null,  
    ability:""
  }];
  return current;
}, {} );
lissettdm
  • 12,267
  • 1
  • 18
  • 39
-1

Let me get this straight: you want that your array contains several attributes having key = playerN and value the struct of a player. Right?

If so, you don't want playerStatus to a list but an object (you can stille iterate it's attributes as you do with an array). So your code turns like this:

const playerStatus = [];
var player = "";
// as said in the comments below there is no need to use the variale index as i is already incrementing and keeping track of index

 for (i = 0; i < playerCount; i++) {
    player = "player" + i;
    playerStatus[player] =
    {
       cardName: "", 
       balanceNum: null,  
       ability:""
    };
    
    // Also i don't see the utility of the other array
 }

Alternatively i suggest you to use a map with key = playerN and value = ObjectPlayer, it's pretty the same but you can use some useful buil-in functions.

Esotopo21
  • 392
  • 1
  • 12