javascript - 如何在 Javascript/angular 中向 JSON 数组添加值?
问题描述
我在我的文件中初始化了这些,它在一个角度应用程序中:
names = ['A','B','C','D'];
const score = [{}];
在进行一些检查当前播放器的处理之后,我想为每个播放器创建一个数组。每个玩家的数组都会单独添加。第一个玩家 A,然后是 B,依此类推,直到名称数组中的最后一个玩家被调用,因为他们正在从另一个页面获取分数。所以,像这样:
{
"A":{
"End#1":{"arrow1": "here the score",
"arrow2": "here the score",
"arrow3": "here the score"
}
},
"B":{
"End#1":{"arrow1": "here the score",
"arrow2": "here the score",
"arrow3": "here the score"
}
},
"C":{
"End#1":{"arrow1": "here the score",
"arrow2": "here the score",
"arrow3": "here the score"
}
},
"D":{
"End#1":{"arrow1": "here the score",
"arrow2": "here the score",
"arrow3": "here the score"
}
}
}
如何动态创建类似 JSON 数组的内容,以便根据名称的数量增加和减少它?另外,怎么可能说名字“A”稍后会有第二个结尾,然后我怎么能输入第二个结尾?
这是实现它的整个角度文件......(https://codepen.io/ArcherMArk/pen/ZVJwyQ),希望这个文件有点帮助
解决方案
如果我正确理解您的问题,您的 JSON 对象的语法应该是这样的:
编辑:从评论中给出的额外链接来看,您似乎根本不需要 JSON 对象,只需要一个数组。编辑以反映这一点。
scores: [
{
id: "A",
endScores: {
"End#1" : [arrowScore1, arrowScore2, arrowScore3],
"End#2" : [arrowScore1, arrowScore2, arrowScore3]
},
},
{
id: "B",
endScores: {
"End#1" : [arrowScore1, arrowScore2, arrowScore3],
"End#2" : [arrowScore1, arrowScore2, arrowScore3]
},
},
{
id: "C",
endScores: {
"End#1" : [arrowScore1, arrowScore2, arrowScore3],
"End#2" : [arrowScore1, arrowScore2, arrowScore3]
},
},
...
]
然后你会做
for (var i = 0, i < scores.length; i++ ) {
if (scores[i].id === "A") {
scores[i].endScores["End#3"] = [newArrowScore1, newArrowScore2, newArrowScore3];
}
}
请注意 - 您不会向数组添加任何新条目,您只是向对象添加一个新数组,其中“End#n”作为键。
请记住,如果您将“分数”设置为对象/类的属性并在该类中的函数中引用它,那么您应该使用this.scores
.
推荐阅读
- node.js - 数据库不接受新条目 - 带有 mongoose 和 express.js 的 mongodb
- javascript - 单击后如何将函数返回值分配给变量以供以后在javascript中使用?
- java - 在 Java 10 中使用 Apache POI 时出错
- amazon-web-services - 使用 AWS Kinesis Firehose 写入 S3 存储桶中的特定文件夹
- paste - 使用 Linux 将两个文件粘贴到一个文件中
- r - 在 R 数据表中创建列会生成警告“条件的长度 > 1,并且只会使用第一个元素”
- python - 字典和列表的交集?
- algorithm - 用一个具体的例子来理解 Big-O
- mysql - 对于媒人中的每个选项,确保每个选项至少匹配一个(但不超过一个)
- php - 如何使用 PHP 从 Google Cloud SQL 连接和检索数据?