Search code examples
javascriptarraysdictionaryjavascript-objects

How can I fix this? Can't pass the value of variable into a Javascript dictionary


If you look at the lines that I have commented out, you can understand my issue quicky
Code:

        var x;

        for (var x = 0; x < users['suggestions'].length; x++) {

        var thisUser;
        thisUser = users['suggestions'][x].username;   // Returns the username --> John

        var User = {

            thisUser :                                // The value doesn't get copied here

            {
            'user': users['suggestions'][x].username,
            'bio': users['suggestions'][x].bio,
            'id': users['suggestions'][x].id,
            }
};
            newArray.push(User); 
    }

Result:

    {
        "thisUser": {
            "user": "John",
            "bio": "Hello, im new!",
            "id": 23
        }
    },

I have also tried doing ${thisUser} but it doesn't seem to work.

This is the result that I'd like to have

    {
        "John": {
            "user": "John",
            "bio": "Hello, im new!",
            "id": 23
        }
    },

Any tips would be appreciated!


Solution

  • Try using bracket notation:

    var User = {}
    User[thisUser] = {
          'user': users['suggestions'][x].username,
          'bio': users['suggestions'][x].bio,
          'id': users['suggestions'][x].id,
    };