Home > other >  JavaScript: trying to show content of an array object into InnerHTML
JavaScript: trying to show content of an array object into InnerHTML

Time:10-18

I'm fetching some information from the TMDb API and I'm showing it on the screen using InnerHTML, but I've hit a wall trying to display the name of genres that a movie has, because they're stored in a array. I want to show all the genres, some movies have more than one.

That's my code fragment (first time using JavaScript):

//TMDB INTEGRATION - API KEY

const API_KEY = 'api_key=APIKEYNUMBER';
const BASE_URL = 'https://api.themoviedb.org/3/';
const API_LANGUAGE = '&language=pt-BR';
var ID = '299536';
const API_MOVIE = BASE_URL   'movie/'   ID   '?'   API_KEY   API_LANGUAGE;

const overviewfilme = document.getElementById('overviewfilme');

detalheFilme(API_MOVIE);

function detalheFilme(url) {
    fetch(url)
        .then(res => res.json())
        .then(data => document.getElementById("colunaesquerda").innerHTML =
            `
    <h3 id="nomedofilme">${data.title}</h3>
    <h5 style="font-style: italic">${data.original_title}</h5>
    <table>
    <tr>
        <td style="padding-right: 10px;">
            <h6>${data.release_date}</h6>
        </td>
        <td style="padding-right: 10px;">
            <h6>${data.genres[0].name}</h6> //THE SPECIFIC LINE
        </td>
        <td style="padding-right: 10px;">
            <h6>${data.runtime} mins</h6>
        </td>
    </tr>

Currently I'm using the index of the array, so I get the show only the first genre. I've used data.genres.join() and data.genres.join.toString(), but most of the time all I get is [object Object], [object Object], [object Object] (in this example, the movie has three genres).

Can someone help display all the contents of the array?

Thanks!

CodePudding user response:

Your join isn't working because you need to extract the name from each object in the genres array which you can do with map() and then use join().

Something like:

<h6>${data.genres.map(o => o.name).join(', ')}</h6>

CodePudding user response:

As I can see response has an array of objects of genres. You need to extract the name of the genre. You can use Array.map to extract the name.

fetch(url)
    .then((res) => res.json())
    .then(
      (data) =>
        (document.getElementById("colunaesquerda").innerHTML = `
    <h3 id="nomedofilme">${data.title}</h3>
    <h5 style="font-style: italic">${data.original_title}</h5>
    <table>
    <tr>
        <td style="padding-right: 10px;">
            <h6>${data.release_date}</h6>
        </td>
        <td style="padding-right: 10px;">
            <h6>${data.genres.map(({name}) => name).join(", ")}</h6> //THE SPECIFIC LINE
        </td>
        <td style="padding-right: 10px;">
            <h6>${data.runtime} mins</h6>
        </td>
    </tr>`)
    );
  • Related