0

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!

greensky
  • 19
  • 5
  • 1
    check https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name. `{[thisUser]: { //user data }}` – James Aug 15 '22 at 19:04

1 Answers1

0

Try using bracket notation:

var User = {}
User[thisUser] = {
      'user': users['suggestions'][x].username,
      'bio': users['suggestions'][x].bio,
      'id': users['suggestions'][x].id,
};
mykaf
  • 1,034
  • 1
  • 9
  • 12