I'm a beginner at node.js and ran into an error. So I have an object that is called roomCards and stores details related to the cards that players have using the player id as a key and their card as a value. Now the issue is, I can't access the player cards by using exactly the same playerId as it comes up as undefined. Here is the object I'm dealing with.
roomCards = {
roomId:5,
deckCards:[ '2C', '2D', '2H', '2S', '3C', '3D',
'3H', '3S', '4C', '4D', '4H', '4S',
'5C', '5D', '5S', '6C', '6D', '6H',
'6S', '7C', '7D', '7H', '7S', '8C',
'8D', '8H', '8S', '9C', '9D', '9H',
'9S', '10D', '10H', '10S', 'AC', 'AD',
'AH', 'AS', 'JC', 'JH', 'JS', 'KD',
'KH', 'KS', 'QC', 'QD', 'QH', 'QS'],
'W48PoPabFUSN9r-iAAAC': [ '5H', 'JD', 'KC' ] --------- this is the value i'm trying to access using the playerId key
}
Any help would be greatly appreciated. Have an amazing day ahead :)))
-
Please show what you tried that isn't working and provide the specific error details as per minimal reproducible examplecharlietfl– charlietfl2020年08月22日 18:16:30 +00:00Commented Aug 22, 2020 at 18:16
-
@charlietfl, Apologies for that, I keep getting an "undefined" value whenever I try to access the value of my playerId : 'W48PoPabFUSN9r-iAAAC'Jesus Johan Godinho– Jesus Johan Godinho2020年08月22日 18:31:51 +00:00Commented Aug 22, 2020 at 18:31
-
Try to access it with what code?charlietfl– charlietfl2020年08月22日 18:35:39 +00:00Commented Aug 22, 2020 at 18:35
2 Answers 2
Whenever you are using a string literal as a key, the regular dot operator (.) doesn't work. In such cases, you will have you reference such keys using [].
So, in your case, assuming that the player id is stored in a variable name playerId, you can reference to that particular property using:
roomCards[playerId].
var roomCards = {
roomId:5,
deckCards:[ '2C', '2D', '2H', '2S', '3C', '3D',
'3H', '3S', '4C', '4D', '4H', '4S',
'5C', '5D', '5S', '6C', '6D', '6H',
'6S', '7C', '7D', '7H', '7S', '8C',
'8D', '8H', '8S', '9C', '9D', '9H',
'9S', '10D', '10H', '10S', 'AC', 'AD',
'AH', 'AS', 'JC', 'JH', 'JS', 'KD',
'KH', 'KS', 'QC', 'QD', 'QH', 'QS'],
'W48PoPabFUSN9r-iAAAC': [ '5H', 'JD', 'KC' ]
};
var playerId = 'W48PoPabFUSN9r-iAAAC';
console.log(roomCards[playerId]);
12 Comments
try this
roomCards["W48PoPabFUSN9r-iAAAC"]