1

Olá, como faço para pegar o elemento "name", sendo que ele está dentro de "show" e todo o "show" está dentro do "0"? (OBS: Se a nomenclatura tiver errada, me desculpem, sou iniciante no JS)

0:
score: 31.86105
show:
externals: {tvrage: 18164, thetvdb: 81189, imdb: "tt0903747"}
genres: (3) ["Drama", "Crime", "Thriller"]
id: 169
image: {medium: "http://static.tvmaze.com/uploads/images/medium_portrait/0/2400.jpg", original: "http://static.tvmaze.com/uploads/images/original_untouched/0/2400.jpg"}
language: "English"
name: "Breaking Bad"//quero por em uma variavel
network: {id: 20, name: "AMC", country: {…}}
officialSite: "http://www.amc.com/shows/breaking-bad"
premiered: "2008-01-20"
rating: {average: 9.3}
runtime: 60
schedule: {time: "22:00", days: Array(1)}
status: "Ended"
summary: "<p><b>Breaking Bad</b> follows protagonist Walter White, a chemistry teacher who lives in New Mexico with his wife and teenage son who has cerebral palsy. White is diagnosed with Stage III cancer and given a prognosis of two years left to live. With a new sense of fearlessness based on his medical prognosis, and a desire to secure his family's financial security, White chooses to enter a dangerous world of drugs and crime and ascends to power in this world. The series explores how a fatal diagnosis such as White's releases a typical man from the daily concerns and constraints of normal society and follows his transformation from mild family man to a kingpin of the drug trade.</p>"
type: "Scripted"
updated: 1558526237
url: "http://www.tvmaze.com/shows/169/breaking-bad"
webChannel: null
weight: 93
_links: {self: {…}, previousepisode: {…}}
__proto__: Object

xhr.open('GET', `http://api.tvmaze.com/search/shows?q=${serie}`)

    xhr.addEventListener('load', function(){
        var api = (xhr.responseText)
        var recebidos = JSON.parse(api)
            console.log(recebidos)
        });

    xhr.send()

2 Respostas 2

1

Legal que esteja aprendendo Javascript, então para você acessar elementos dentro de um array você tem que indicar seu índice, ou seja, no caso como todo o retorno da API está dentro de 1 array você pode acessar assim:

let dados = [
  {
    "score": 13.49527,
    "show": {
      "id": 8044,
      "url": "http://www.tvmaze.com/shows/8044/altersgluhen-die-serie",
      "name": "Altersglühen - Die Serie",
      "type": "Scripted",
      "language": "German",
      "genres": [
        "Romance"
      ],
      "status": "Ended",
      "runtime": 25,
      "premiered": "2014-11-13",
      "officialSite": null,
      "schedule": {
        "time": "23:15",
        "days": []
      },
      "rating": {
        "average": null
      },
      "weight": 0,
      "network": {
        "id": 508,
        "name": "WDR",
        "country": {
          "name": "Germany",
          "code": "DE",
          "timezone": "Europe/Busingen"
        }
      },
      "webChannel": null,
      "externals": {
        "tvrage": 45397,
        "thetvdb": null,
        "imdb": null
      },
      "image": {
        "medium": "http://static.tvmaze.com/uploads/images/medium_portrait/29/73542.jpg",
        "original": "http://static.tvmaze.com/uploads/images/original_untouched/29/73542.jpg"
      },
      "summary": "<p>Seven women and six men, almost all beyond the 70, gather for speed dating. The special thing: 13 actors, 19 cameras - but no script and no repeat. Only on the basis of character profiles can be a a high-caliber ensemble of actors to intense encounters, supported by empathy and the art of improvisation. The television movie Altersglühen – Speed Dating für Senioren by Jan Georg Schütte told the Speed Dating as a whole. <b>Altersglühen - Die Serie</b> - cut from the same rotating material - concentrates per episode to a single character who accompanies them through the meeting.</p>",
      "updated": 1477191187,
      "_links": {
        "self": {
          "href": "http://api.tvmaze.com/shows/8044"
        },
        "previousepisode": {
          "href": "http://api.tvmaze.com/episodes/445117"
        }
      }
    }
  }
]

console.log(dados[0].show.name);

Caso tiver outros elementos show.name você poderia acessar seus elementos por métodos como map() ou forEach().

2
  • Era isso mesmo que eu precisava. Muito obrigado mesmo! Commented 15/06/2019 às 21:37
  • Legal Thales, bons estudos!
    – LeAndrade
    Commented 15/06/2019 às 21:39
0

O resultado desse pedido será um array de objectos contendo toda a informação.
Para iterar esse array e imprimir o nome de cada item podes fazer assim:

api.forEach(item => console.log(item.show.name));

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .