Search code examples
javascriptfiltermethodsincludefetch-api

Why the filter method is not working when filtering an array of objects requested from an API (Javascript)


I have been practicing some coding after some break. I'm trying to filter an array of objects from an api and creating a function the which will return me every word from the title of the fetch I'm making the request.

However, when I want to do the filter it shows that filter method is not recognized, and I don't know if its affected if you are filtering an array that you called from an api.

This is the code.

function titles(word){
    let sentence
    let array = []
    let api = 'https://jsonplaceholder.typicode.com/posts'
    let data = fetch(api)
    let response = data.then(res => res.json()).then(data => data.map((e) => { e.title}))
    array = array.concat(response)
    sentence = Promise.all(array.flat()).then(results => results.flat())
  const people = sentence.filter(e => e.title.includes(word))
    return people
}

However, returns an error message (see image)

But when I do the same on an array of objects the filter works well.

I appreciate any help, feedback and code improvement. Thanks in advance!

error message


Solution

  • Here we have to take a look at the part where you are trying to extract the data. Adding a proper way to fetch by converting it to JSON will help. using data.json() after which you can filter. Conforming with your code flow, now after this, you can use the filter option.

    You can find working code here

       async function titles(word) {
          const sentence = [];
          const api = "https://jsonplaceholder.typicode.com/posts";
          const data = await fetch(api);
          const response = await data.json();
          const titles = response.map(({ title }) => title);
          sentence.push(...titles);
          const people = sentence.filter((title) => title.indexOf(word) > -1);
          return people;
        }