首页 > 解决方案 > 如何在 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),希望这个文件有点帮助

标签: javascriptarraysjsonangular

解决方案


如果我正确理解您的问题,您的 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.


推荐阅读