简体   繁体   中英

Setting nested object properties in JavaScript

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

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]);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM