javascriptarrays

I am getting [object, object] from a nested array from the Marvel API while using the map function


I am getting input which a superhero from marvels api and I can see the description name and id but when it comes to series comics and events which are collections i can not display them correctly.

I have tried using the map function. Everything works besides the nested array.

This is the output in the console log:

enter image description here.

document.querySelector("button").addEventListener("click", fetchGetSuper)

function fetchGetSuper() {
  const superChoice = document.querySelector("input").value
  const imageSize = "standard_fantastic"`)
    .then(response => {
      if (!response.ok) {
        throw Error("ERROR");
      }
      return response.json();
    })
    .then(data => {
      console.log(data.data.results);
      var html = data.data.results.map(comic => {
          return `<div class="comics">
                    <p>Name: ${comic.name} </p>
                    <p>Description: ${comic.description} </p>
                    <img src = "${comic.thumbnail.path}/${imageSize}.${comic.thumbnail.extension}">
                    <ul>
                      <li><p>${comic.urls}<p></li>
                    </ul>
                 </div>`;
        })
        .join("")
      console.log(html);
      document.querySelector(`#cards`).insertAdjacentHTML("afterbegin", html);

    })
    .catch(error => {
      console.log(error);
    });
}
<input>
<button>Get a Marvel</button>
<div id="cards"></div>


Solution

  • You can't access name and resourceURI because they are nested in the items property which is an array.

    The items array is a property of the comics key, which is in the index 0 of the results array. As results is an Array(1), can access comics with data.data.results[0].comics and then, map items to access what is inside the items array