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!
2
Answers
Your code has some incorrect usage.
async
function to handle the Promise response;data.map
function is wrong, it does not return an array of objectsPromise.all
function;array.flat
function, the data array returned by the API is just one level.refs
https://jsonplaceholder.typicode.com/posts
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 toJSON
will help. usingdata.json()
after which you canfilter
. Conforming with your code flow, now after this, you can use thefilter
option.You can find working code here