I am working on app and I am trying to extract three attributes of this string (I thought it was an array of objects is filteredResultsJSON, but it is a string) :
Well, when I want to get the news of a given section I am using this code:
export default function getNewsFilteredBySection (sectionSearched="") {
const URL= `https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=${API_KEY}`;
return fetch(URL)
.then(res=>res.json())
.then(response=> {
const { data = [] } = response;
if(Array.isArray(data)){
const {results} = response;
const filteredResults = results.filter(obj => {
return obj.section === sectionSearched;
});
const filteredResultsJSON = JSON.stringify(filteredResults);
const name = typeof(filteredResultsJSON);
console.log(name);
return filteredResultsJSON;
}
})
};
I did JSON.stringify(filteredResults) because I saw it when doing console.log()as an [Object Object] and I wanted to be able to read the information and to loop through it to be able to extract it.
So I am using this code to extract the attributes I want for each news:
export function getNewsAttributes (filteredResultsJSON=[]) {
const newsAttributes = filteredResultsJSON.map(filteredResultJSON=>{
const { title, abstract, url } = filteredResultJSON;
console.log(title, abstract, url);
return {title, abstract, url};
});
return newsAttributes;
};
But it returns the following error:
I have been researching and I totally think the matter is about JSON.Stringify(filteredResults). How could I maintain that variable as an object, being able to read it and extract the information from it?
I am going to use it like this, after an onClick event:
function showEvent (e) {
const sectionSearched = e.target.innerText;
const filteredResultsJSON = getNewsFilteredBySection(sectionSearched);
const newsAttributes = getNewsAttributes(filteredResultsJSON);
}
Thanks a lot :)
CodePudding user response:
I solved it with this code:
export default function getNewsFilteredBySection (sectionSearched="") {
const URL= `https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=${API_KEY}`;
return fetch(URL)
.then(res=>res.json())
.then(response=> {
const { data = [] } = response;
if(Array.isArray(data)){
const {results} = response;
const filteredResults = results.filter(obj => {
return obj.section === sectionSearched;
});
console.log(filteredResults);
return filteredResults;
}
})
};
Finally I didnt need to do JSON.Stringify(filteredResults). However I am having this two errors and I dont know why, my app works:
Any idea? Thanks a lot :)
CodePudding user response:
You need to add async
export default async function getNewsFilteredBySection (sectionSearched=""){ ...
async function showEvent (e) { ...
and await
const filteredResultsJSON = await getNewsFilteredBySection(sectionSearched);



