-1

I am creating a deck of card objects in JavaScript. Why do all the objects hold the same keys and values? Here is my code

                for(var i = 0; i<4; i++){
                    for(var j = 0; j<13; j++){
                        cardObj["Suit"] = arrSuits[i];
                        //console.log(arrSuits[i]);
                        cardObj["Value"] = arrCardNums[j];
                        //console.log(arrSuits[i]);
                        arrObjectCards.push(cardObj);
                    }
                }
                console.log(arrObjectCards);
            }

Here is a photo of my issue: enter image description here

Anyone know the source of this error?

  • 2
    You only have one object. You just mutate it and push a new reference to it into the array each time you go around the loop. There must be loads of duplicates of this. – Quentin May 06 '22 at 17:20
  • Please post a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) so we know all variables at play. What's `arrSuits`? What's `arrCardNums`? It's hard to debug without knowing these. – user1599011 May 06 '22 at 17:20
  • You keep pushing and changing the same object over and over. – connexo May 06 '22 at 17:20
  • @connexo Here is arrSuits - var arrSuits = ["Diamonds","Spades","Clubs","Hearts"]; – Matthew Hart May 06 '22 at 17:21
  • Here is arrCardNums - var arrCardNums = ["Ace","2","3","4","5","6","7","8","9","10","K","Q","J"]; – Matthew Hart May 06 '22 at 17:21
  • 1
    Again, all your array elements reference **the same** `cardObj`. You need to create a new object in each loop cycle. – connexo May 06 '22 at 17:23
  • 1
    Place `const cardObj = {}` in the most inner for-loop. This change will use a new object for each card. – 3limin4t0r May 06 '22 at 17:28

0 Answers0