I’m trying to display some information from RAWG.io API (https://api.rawg.io/api/games) but some of them are indented so the output is not what I want (for example in game genres). My code is

<template>
  <div>
    <v-container fluid v-if="game !== null">
      <v-row class="frist">
        <v-col class="title">
          <h1>{{game.name}}</h1>
        </v-col>
        <v-col class="info">
          <p>{{game.genres}}</p>
        </<-col>
      </v-row>
  </div>
</template>

<script>
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
export default {
  name: "game",
  data() {
    return {
      gameId: this.$route.params.gameId,
      title: "game",
      game: null
    };
  },
  mounted() {
    Vue.axios
      .get("https://api.rawg.io/api/games/" + this.gameId)
      .then(resp => {
        this.game = resp.data;
        console.log(resp.data);

        console.warn(resp.data.results);
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

{{game.genres}} returns:

[
  {
    "id": 4,
    "name": "Action",
    "slug": "action",
    "games_count": 93639,
    "image_background": "https://media.rawg.io/media/games/84d/84da2ac3fdfc6507807a1808595afb12.jpg"
  },
  {
    "id": 3,
    "name": "Adventure",
    "slug": "adventure",
    "games_count": 64820,
    "image_background": "https://media.rawg.io/media/games/4be/4be6a6ad0364751a96229c56bf69be59.jpg"
  }
]

How do I display only “name” in the genres attribute?

Answer

A simple approach would be to use a mapped, computed property:

<!-- ... -->
        <v-col class="info">
          <p>{{genreNames}}</p>
        </v-col>
<!-- ... -->
<script>
// ... just posting the important parts
export default {
  // ...
  computed: {
    genreNames() {
      return this.game.genres.map(({ name }) => name).join(' ') // join the names with a space
    }
  }
}
</script>

Write a comment

Your email address will not be published. Required fields are marked *