Iterating through an array of objects within a Vuejs template

Consider the JSON data below:

{
  "games": [
    {
      "id": 1,
      "init_date": "2020-02-11T07:47:33.627+0000",
      "players_in_game": [
        {
          "id": 1,
          "player": {
            "id": 1,
            "player": "Jack Bauer",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02682c6063776770426176772c656d7430">[email protected]</a>"
          }
        },
        {
          "id": 2,
          "player": {
            "id": 2,
            "player": "Chloe O'Brian",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8eeda0e1ecfce7efe0ceedfafba0e9e1f8">[email protected]</a>"
          }
        }
      ]
    },
    {
      "id": 2,
      "init_date": "2020-02-11T08:47:33.627+0000",
      "players_in_game": [
        {
          "id": 3,
          "player": {
            "id": 1,
            "player": "Rome Jones",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cea4e0acafbbabbc8eadbabbe0a9a1b8fc">[email protected]</a>"
          }
        },
        {
          "id": 4,
          "player": {
            "id": 2,
            "player": "Ludacris",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e1acede0f0ebe3ecc2e1f6f7ace5edf4">[email protected]</a>"
          }
        }
      ]
    },
  ]
}  

I am looking to display a Player VS another player for each 'players-in-game' entry, like so:

**PLayer 1   VS    PLayer 2**
Jack Bauer         Chloe O'Brian
Rome Jones         Ludacris

However, I'm having trouble with the implementation. Here is the code snippet I have tried:

<tr v-for="(general, index) in getGamesAll.games" v-bind:key="index">
  <td>Game {{general.id}}</td>
  <td v-for="(gamePlayer, j) in general" :key="j">

    {{general.players_in_game.player.player}}
  </td>
  <td>vs</td>
   <td v-for="(gamePlayer, j) in general" :key="j">
     {{general.players_in_game.player.player}}
  </td>
</tr>

This approach is flawed as it does not specify which player within the 'players-in-game' object to access. What would be the correct way to achieve this desired output?

Answer №1

It was crucial to pinpoint the correct node during the loop.

In this scenario, 'general' signifies one of the elements in 'getGamesAll'.

After entering that particular 'general' instance, we aim to perform a second loop based on the array at node 'players_in_game'.

Instead of iterating over the same object twice for each row representation, the goal is to find a method to accomplish it with just one loop. In this code snippet, I'm utilizing a single td element and conditionally including the 'vs' message.

var getGamesAll = {
  "games": [
    {
      "id": 1,
      "init_date": "2020-02-11T07:47:33.627+0000",
      "players_in_game": [
        {
          "id": 1,
          "player": {
            "id": 1,
            "player": "Jack Bauer",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73195d1112061601331007065d141c0541">[email protected]</a>"
          }
        },
        {
          "id": 2,
          "player": {
            "id": 2,
            "player": "Chloe O'Brian",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0665286964746f67684665727328616970">[email protected]</a>"
          }
        }
      ]
    },
    {
      "id": 2,
      "init_date": "2020-02-11T08:47:33.627+0000",
      "players_in_game": [
        {
          "id": 3,
          "player": {
            "id": 1,
            "player": "Rome Jones",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="147e3a7675617166547760613a737b6226">[email protected]</a>"
          }
        },
        {
          "id": 4,
          "player": {
            "id": 2,
            "player": "Ludacris",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8bbf6b7baaab1b9b698bbacadf6bfb7ae">[email protected]</a>"
          }
        }
      ]
    },
  ]
}

new Vue({
el:"#players",
data:{
  getGamesAll: getGamesAll
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<table id="players">
<tr v-for="(general, index) in getGamesAll.games" v-bind:key="index">
  <td>Game {{general.id}}:</td>
  <td v-for="(gamePlayer, j) in general.players_in_game" :key="j">
    {{gamePlayer.player.player}} <span v-if="j<1">vs</span>
  </td>
</tr>
</table>

Answer №2

If you want to locate specific players by their id, you can do so using the following method:

function fetchPlayers(data, playerID) {

    const foundPlayers = data.map(entry => { // loop through each game entry
        return entry.players_in_game.map(player => { // loop through each player in the game
            if (player.player.id === playerID) {
                return player.player;
            }
        }).filter(uniquePlayer => uniquePlayer); // remove duplicate players
    });

    return foundPlayers; // Return players with matching id
}
fetchPlayers(gameData.games, 2);

The expected output would be:

https://i.sstatic.net/J6PeY.png

After that, you can use this template...

<tr v-for="(game, index) in gameList.games" v-bind:key="index">
  <td>Game {{game.id}}</td>

  <td v-for="firstPlayer in fetchPlayers(gameList.games, 1)">
    {{ firstPlayer }}
  </td>

  <td>VS</td>

   <td v-for="secondPlayer in fetchPlayers(gameList.games, 2)">
    {{ secondPlayer }}
  </td>
</tr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent those pesky popups with this handy script

Even though AdBlock sometimes doesn't block popups, I have a solution in mind. I plan to use Greasemonkey and jQuery to create my own popup blocker. Is it possible to intercept the clicks and determine if a popup is about to open? $('.popupLaun ...

What are the benefits of installing both libraries A (react-router) and B (react-router-dom) together, especially when library B relies on library A for functionality

I am currently exploring the necessity of explicitly specifying all dependencies in the packages.json file. For instance, when I want to utilize the react-router library. According to the official documentation: npm install react-router@6 react-router-d ...

Instructions on adding a class to the parent element when the child has a particular class

Here is the html structure I am working with: <section> <div class="v-middle"> <div class="row"> <h5 class="heading">Heading goes here</h5> </div> </div> </section> ...

VueJS does not show a component if it is contained within a v-if or v-show directive

My goal is to show a component when the 'Add Patient' button is clicked using a v-if directive: // within <template></template> <button type="button" class="btn btn-info" @click="showPatientForm">Ad ...

Utilize Vuetify to showcase a vertical layout consisting of a header and a v-card, occupying the full height

<template> <div> <div style="height: 20px; color: yellow"> test </div> <v-card class="markdown-preview" tile> <v-card-text v-html="previewText"> </v-card-text> ...

Elegant Bootstrap 4 Carousel featuring a glimpse of the upcoming slide alongside the primary carousel item

I am in search of a straightforward Bootstrap 4 carousel that showcases a glimpse of the next slide on the right. Despite exploring similar questions, I have not found a suitable solution. The links to those questions are: 1)Bootstrap carousel reveal part ...

Can anyone provide a solution for determining the number of active intervals in Javascript?

Similar Question: How to View All Timeouts and Intervals in JavaScript? I've been working on an HTML5 game that includes a lot of graphical effects using intervals created by the setInterval function. However, I've noticed that my game is ru ...

Tips for incorporating a variable into a JSON object value when dynamically constructing an object

Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result. var characters = ['Iron Man', ...

Can you choose an option from a dropdown menu without relying on jQuery?

Can a dropdown list item be selected using AngularJS instead of jQuery? I have successfully accomplished this using jQuery, but I am curious if it can be done with AngularJS. This is how I achieved it using jQuery: var dropdownlist = $("select").data("k ...

Using VueResource to send a GET request in Vue.js returned a response with a status

There is an issue I am facing with sending a request to the API to retrieve all users. The login function is called (index.vue) and it attempts to access api/users/all which should return all the users in that collection. Using Postman, the API returns th ...

Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the ...

Transfer an object to $state.go

I'm having trouble solving this issue. Here's the state I am working with: var myState:ng.ui.IState = <ng.ui.IState> { url: '/new/{order.orderNumber}', controller: 'OrderController', controll ...

Unable to find module reference "three" at 137

Returning to an older project, I realized that nothing was loading. When I checked the console log, this is what I found: Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". In my ...

Trigger a function in JavaScript by clicking on an element and passing its class

I have written the following code: <?php $extCount = 0; foreach($this->externalReferal as $externalReferal) { $extCount++; ?> <div class='fieldtestPct' > <div class='fieldItemLabel'> < ...

Using JQuery to Load a CSHTML File into a Modal in C#

I am attempting to have the content of one specific page loaded into a modal on a different page when a button is clicked. Unfortunately, I am encountering an issue where not only the desired content from the specified page is loading, but also content fro ...

Injecting a JavaScript object into an HTML string

I am facing an issue with a JavaScript variable I have, which points to a specific DOM element that I want to display somewhere else within the DOM structure. Here is how it is defined: var salesRep = $("ul.map").attr("id","1"); My goal is to pass this v ...

AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name. Once the 'nameService& ...

Using Rxjs to handle several requests with various headers

I have a specific requirement where, if hasProcessado == true, 10 additional requests should be made before issuing the final request. If the final request fails, 3 more attempts are needed. Furthermore, when sending the last request, it is essential to n ...

Pass data to PHP using AJAX

Is it possible to pass the variable rowNumber to the PHP file dataSource in this code? function getData(dataSource, divID,rowNumber) { if(XMLHttpRequestObject) { var obj = document.getElementById(divID); XMLHttpRequestObject.open("GET", dataSo ...

Launch the file explorer using JavaScript/HTML

Is there a way to launch a real explorer window instead of the browser's directory look? For example, like the windows key + e window... Is there a method using html or JavaScript? I've noticed it in a Firefox add-on called new tab king, but I c ...