2

I wish to insert variables into an object key structure but I just get the variable name rather than the variable value.

var winnerId = 10;
var loserId = 11;        

newMessage.setMessageData({
  winnerId : {
    "status" : "win",
    "choice" : playerData[winnerId]["currentChoice"],
    "newScore" : playerData[winnerId]["score"]
  },
  loserId : {
    "status" : "lost",
    "choice" : playerData[loserId]["currentChoice"],
    "newScore" : playerData[loserId]["score"]
  }           
});
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
Keith Power
  • 13,891
  • 22
  • 66
  • 135
  • 1
    I feel like a broken record a bit, but it always feels useful to point out that what you're describing has nothing to do with JSON. It's just a plain old *object*. JSON is a `string` that *represents* an object. – Tyler Roper Feb 22 '19 at 01:36
  • good to know thanks. I am sure it has been said many times :-) – Keith Power Feb 22 '19 at 01:46

1 Answers1

5

You should use computed-property-names:

newMessage.setMessageData({
    [winnerId]: {
        "status": "win",
        "choice": playerData[winnerId]["currentChoice"],
        "newScore": playerData[winnerId]["score"]
    },
    [loserId]: {
        "status": "lost",
        "choice": playerData[loserId]["currentChoice"],
        "newScore": playerData[loserId]["score"]
    }
});
SocialDev
  • 68
  • 3