-1

is there a simplest way of iterating over an array of arrays in this sample of JSON


  "game": {

  "sunk_ships": [
    [
      "PatrolBoat",
      "Destroyer"
    ]
  ]
}

in my code this is what i wrote having in mind former questions answered

for (let i = 0; i < this.getGamePlayerId.sunk_ships.length; i++) {
          let childArray=parent[i];

          for (let j = 0; j < parent[i].length; j++) {
            var innerValue=parent[i][j]
            console.log(parent[i][j]);

              document
                .getElementById(innerValue)
                .classList.add("shipDestroyed");
          }
        }

thanks

Enrique GF
  • 1,215
  • 3
  • 16
  • 35
  • hi, please show us the code you tried – niccord Feb 05 '20 at 14:47
  • 1
    Does this answer your question? [looping through arrays of arrays](https://stackoverflow.com/questions/7106410/looping-through-arrays-of-arrays) – 404 Feb 05 '20 at 14:48
  • If you are using v-for in vue then you might also look at the conditional binding of classes. This could allow you to change colors or icons based on your destroyed ship values. https://vuejs.org/v2/guide/class-and-style.html – Dean Feb 05 '20 at 14:55

1 Answers1

0

JSON is textual data exchange format.

What you are trying to write is a nested loop, which there are lots of ways to write.

const json = `{
    "game": {

        "sunk_ships": [["PatrolBoat", "Destroyer"], ["Frigate", "Carrier"]]
    }
}`;

const o = JSON.parse(json)

o.game.sunk_ships.forEach((ships) => 
                          ships.forEach((ship) => 
                              console.log(ship)))
Ben Aston
  • 53,718
  • 65
  • 205
  • 331