How is it possible to add values to a JSON array in Javascript/angular?

Tags: , , ,



I have these initialized in my file, which is in an angular app:

  names = ['A','B','C','D'];

  const score = [{}];

After doing some processing which is working to check the current player, I want to create an array for each player. Each player’s array gets added individually. First player A, then B, and so on until the last player in the names array gets called, as they are getting scores from another page. So, like this:

 {
  "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"
             }
      }
  }

How can I create something like this JSON array on the fly, so that I can increase and decrease it, depending on the number of names? Also, how is it possible to say that name “A” will have a second end later how can I then enter the second end?

this is the whole angular file where it sould get implemented… ( https://codepen.io/ArcherMArk/pen/ZVJwyQ ), hope this file helps a bit

Answer

If I understand your question correctly, the syntax for your JSON object should be something like this:

Edit: from the extra link given in comments, it seems you don’t need a JSON object at all, just an array. Edited to reflect that.

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]
        },
    },

    ...

]

You would then just do

for (var i = 0, i < scores.length; i++ ) {
    if (scores[i].id === "A") {
        scores[i].endScores["End#3"] = [newArrowScore1, newArrowScore2, newArrowScore3];
    }
}

Just a note – you wouldn’t be adding any new entries to an array, you’re just adding a new array to an object, with “End#n” as the key.

Remember, if you’re setting ‘scores’ as a property of an object/class and referring to it in a function within that class, then you should use this.scores.



Source: stackoverflow