How to manipulate strings inside array from a fetch response?

Viewed 31

I am looking for some assistance with my fetch response from the Online Movie Database API . I am able to succesfully get a response to log in the console, which is what I want. However I am trying to manipulate the response.

I want to pull the most popular shows from the API (API sends 100 titles), and trim it down to 8 titles. I did that using the .splice method. It returns an array of 8 strings representing a title id.

Example: '/title/tt11198330'

Lastly I want to trim each 8 of the strings so it gets rid of the /title/ and all I have left is tt11198330. I am trying to do this inside the .then and when I console.log that forEach that is saved as 'trimmer' it gives me undefined instead of the trimmed result I was intending. But if I console.log the element in the forEach it does show the trimmed strings. Any idea why its undefined, and is there maybe a better way to go about this?

// fetch for most popular shows
const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': 'Z2EvqnO4xwmsh2eY3rMTIV2ivj5hp1QsuGUjsnrYp69UBS4EI5',
        'X-RapidAPI-Host': 'online-movie-database.p.rapidapi.com'
    }
};

fetch('https://online-movie-database.p.rapidapi.com/title/get-most-popular-tv-shows?currentCountry=US&purchaseCountry=US&homeCountry=US', options)
    .then(response => response.json())
    .then(response => {
        const list = response.splice(0, 8)

        let trimmer = list.forEach(element => console.log(element.slice(7, 17)))
        console.log(trimmer)


    })
    .catch(err => console.error(err));

1 Answers

because you are using forEach and it doesn't return data, use map instead.

fetch('https://online-movie-database.p.rapidapi.com/title/get-most-popular-tv-shows?currentCountry=US&purchaseCountry=US&homeCountry=US', options)
    .then(response => response.json())
    .then(response => {
        const list = response.splice(0, 8)

        let trimmer = list.map(element => element.slice(7, 17))
        console.log(trimmer)


    })
    .catch(err => console.error(err));
Related