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:

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

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

Transforming JQuery text upon selecting preloaded content with fire

When I copy the first name into the last name field, everything works fine for new names on the page. However, once a few names have been entered and the browser starts showing a history of names, the function doesn't work anymore if a pre-filled or o ...

Configuring a custom domain for a Rust service on Clever Cloud: A step-by-step guide

After successfully deploying my Rust service to the Clever Cloud platform and testing it on PROD and localhost, I am now facing the challenge of binding my custom domain with the deployed service. I would like to eliminate the need for using the lengthy C ...

Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them. Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle. The script looks like thi ...

Creating a network of communication between API routes in NextJS

Can the fetch API be used within an API route in NextJs? I have a large handler and instead of having everything in one handler, I'd like to modularize it so that after completing a specific task (e.g., writing to a database), I can call another handl ...

The object displays a value when inspected in the console, but appears as null when checked in the controller (Laravel)

In my form object, I have the following fields: { form: { a: '', b: '', c: '', d: '', e: '', f: '', g: '' } } When I chec ...

Tips for streamlining the transfer of essential features from a main project to its duplicate projects

In my Angular project, I have a core repository on GitHub that serves as the foundation for custom client projects. Each time a new client comes onboard, we create a clone of the core project and make customizations based on their requirements. The issue ...

Utilizing the "return" keyword in Javascript outside of function declarations

Exploring the Impact of Using the Return Keyword in JavaScript Scripts Beyond Functions in Browsers and Node.js Recently, I experimented with utilizing the return keyword in a Node.js script like so: #!/usr/bin/env node return 10; My initial assumption ...

problems with hovering over radio buttons in Internet Explorer 9

Encountering a curious issue in IE9: When hovering over my top level wrapper div, the first radio button seems to be triggered as though it's being hovered over. This means that even if the last radio input is selected, clicking anywhere within the wr ...

Issue with Bootstrap.js causing mobile menu to not expand when toggled in Rails app

Despite adding the .toggled class, my hamburger menu is not expanding when I click on the mobile menu. I've tried adjusting the order of the required javascript commands, but it doesn't seem to be working as expected. Here are the steps I'v ...

What is the best way to dynamically adjust the size of a grid of divs to perfectly fit within the boundaries of a container div without surpassing them?

Currently, I am working on a project for "The Odin Project" that involves creating a web page similar to an etch-a-sketch. I have made some progress, but I am facing a challenge with dynamically resizing a grid of divs. The issue lies with the container d ...

Using AJAX autocomplete with Sys.Serialization.JavaScriptSerializer

I implemented an ajax autocomplete feature in ASP.NET where a method from a web service is called to fetch postal codes. public string[] GetNames(string prefixText, int count, String contextKey) { prefixText = prefixText.Trim(); XmlNodeList list; ...

The npm lint command is throwing an "Observable `source is deprecated`" error

When I execute the command npm lint on my code, I receive a warning stating "source is deprecated: This is an internal implementation detail, do not use." The specific part of the code causing this issue is shown below: set stream(source: Observable<a ...

What is the process for generating an HTTP response that results in a pipe error being thrown

In my NestJS application, I have created a custom pipe that validates if a given value is a valid URL. If the URL is invalid, an error is thrown. This pipe is utilized in a controller to save an item into the database. Recently, I discovered that the pipe ...

What sets the target property of the mousewheel event apart from other events like click, mousedown, and touchstart?

The mousewheel event's target property reveals the DOM element currently being hovered over when using the mousewheel or gesture-capable touchpad. In my experience (specifically in Safari 6, I will verify this in other browsers later), the target ret ...

Sort object keys in a Vue component by the English representation of numbers in descending order

I've got some data for a dropdown menu. The list is currently in a random order, but I'd like to arrange it in descending order based on the key values (One, Three, Five, ...). new Vue({ el: '#app', data: { data: { Abc: ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

Eliminating fillers dashes from a text

Imagine having a string filled with soft hyphens like the one below: T-h-i-s- -i-s- -a- -t-e-s-t-.- The goal is to eliminate these soft hyphens and get back the clean string: This is a test. Attempting this task in JavaScript, here's how far I&apo ...

What is the best way to responsively center an after pseudo-element above its parent?

Looking to create a dynamic tooltip without any fixed widths or constraints on the parent element. The process seems simple enough, but I'm facing an issue with centering the after element due to an existing transform attribute of transform: translat ...