Getting information from an "Object"

Asked

Viewed 77 times

0

I’m using an API to get some movie data, but I wanted to get only the "name" information of the genres, which are "Action, Adventure, Comedy, Fantasy". But the number of genera is not always the same, sometimes there are 2, 3..

genres: [
    {id: 28, name: "Ação"},
    {id: 12, name: "Aventura"},
    {id: 35, name: "Comédia"},
    {id: 14, name: "Fantasia"}
]

I’m using the following code:

$.getJSON('https://api.themoviedb.org/3/movie/166426?api_key=MINHA-API&language=pt-BR').then(function(response) {
                    console.log(response.genres);

When using this mode, the console returns 4 Object and inside them id and name information

(4) [Object, Object, Object, Object]

If I use

console.log(response.genres[3].name); 

It returns me the genre of object 3, which is "Fantasia", but if I look for a film that has 2 genres for example, it already error.

1 answer

2


Just use the method map of array and return only the attribute name:

let names = genres.map(genre => genre.name);

Take the example:

const genres = [
    {id: 28, name: "Ação"},
    {id: 12, name: "Aventura"},
    {id: 35, name: "Comédia"},
    {id: 14, name: "Fantasia"}
];

let names = genres.map(genre => genre.name);

console.log(names);

  • Well, with this code he always returns me these 4 genres. Tbm there are other genres that can occur, not only these 4

  • Yes, because I put only 4 in the example. You need to adapt to your problem by putting response.genres.map(genre => genre.name)

  • It worked perfectly, thank you very much.

  • @Yurifrança you can mark the answer as accepted using the button just below the answer score on the left side of the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.