0

How would I add a "property" to an object? I tried: players[data.id].name = data.name; but it's not working. Edit: this worked, thanks for the help guys!:

players[data.id] = {name: "Johnny"};

What I want to achieve: (data.id is already defined)

var players = {};
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id].name]);  ---> Johnny
2
  • If your players object associates a key to a Player object, you can easily do it Commented Oct 23, 2019 at 15:45
  • 1
    You need to store an empty object on players[data.id] before adding properties to it, like: var players = {}; players[data.id] = {}; players[data.id].name = "Johnny"; players[data.id].age = 13;. Or maybe you can write: var players = {}; players[data.id] = {name: "Johnny", age: 13}; Commented Oct 23, 2019 at 15:46

2 Answers 2

1

welcome to stackoverflow ! You need to define what players[data.id] is first.
Then you can assign data to it. In your example, you are only logging the name property of your object, remove the .name to show the whole object.

let data = { id: "test" };
var players = {};
players[data.id] = {}
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id]); 

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I forgot to mention players[data.id] is already defined. Sorry.
@part1cle the same principle still applies, you are only logging the name property of your object.
1

First, you have to declare 'players[data.id]' as an object.
The flow of the code would be like

    var players = {};
    players["dataId"] = {};
    players["dataId"].name = "Johnny";
    players["dataId"].age = 13;
    console.log(players["dataId"].name);

1 Comment

Looks like you included narrative answer text in your code chunk. Just delete the spaces in front of those lines to change that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.