0

I'm trying to create a JSON object which looks something like this:

{
    "scores": [{
        "879212387": {
            "elo": 125
        }, {
        "123768901": {
            "elo": 173
        }
    }]
}

(where the numbers under json.scores are a variable named sid64)

but instead I just get something which looks like this

{
    "scores": [{
        "sid64": {
            "elo": 125
        }, {
        "sid64": {
            "elo": 173
        }
    }]
}

How can I dictate that I'm trying to make the object name a variable and not a string?

Current code:

obj.scores.push({
    sid64:
        {
            elo
        }
    })
ElkTF2
  • 47
  • 6
  • Possible duplicate of [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – Neil Locketz Sep 09 '18 at 18:50

2 Answers2

2

You probably need to use objects computed property name

obj.scores.push({
    [sid64]://rest of the code
brk
  • 48,835
  • 10
  • 56
  • 78
1

Use the computed property syntax:

obj.scores.push({
    [sid64]:
    {
        elo
    }
})

It indicates that you want to use the value of the expression inside [...] as the key, not the string sid64.

Neil Locketz
  • 4,228
  • 1
  • 23
  • 34