[英]Setting nested object properties in JavaScript
How would I add a "property" to an object?如何向 object 添加“属性”? I tried: players[data.id].name = data.name;
我试过了: 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)我想要实现的目标:(data.id 已经定义)
var players = {};
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id].name]); ---> Johnny
welcome to stackoverflow !欢迎来到stackoverflow! You need to define what players[data.id]
is first.您需要先定义players[data.id]
是什么。
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.在您的示例中,您仅记录 object 的name
属性,删除.name
以显示整个 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.首先,您必须将“players[data.id]”声明为 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.