Get information from an "Object"

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 genres is not always the same, sometimes they 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 way, the console returns 4 Object and inside it information id and name

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

If I use

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

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

    
asked by anonymous 26.05.2017 / 23:29

1 answer

2

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

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

See 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);
    
26.05.2017 / 23:50