I'm making a news aggregator using newsAPI, and have everything working - to begin with. But was wondering if the code I use to filter through an object can be made more efficient - meaning fewer lines of code.
So far, it only returns what I need from the raw JSON file, then filters it using a for loop to ignore objects with blank values.
Any help would be great.
if (!error && response.statusCode == 200) {
let data = JSON.parse(body);
let articles = data.articles.map(article => {
return {
"title": article.title,
"date": article.publishedAt,
"image": article.urlToImage,
"description": article.description,
"link": article.url
}
});
let filtered = []
for (let i = 0; i < articles.length; i++) {
if (articles[i].title !== null &&
articles[i].date !== null &&
articles[i].image !== null &&
articles[i].description !== null &&
articles[i].link !== null) {
filtered.push(articles[i])
}
}
console.log(filtered)
res.render("index", { filtered: filtered });
}
array.reduceto transform each object. Chain them to avoid intermediates and you are done.const keys = [["title", "title"], ["publishedAt", "date"], ["urlToImage", "image"], ["description", "description"], ["url", "link"]]; res.render("index", { filtered: JSON.parse(body).articles .filter(article => keys.some(key => article[key[0]] !== null)) .map(article => keys.reduce((art, k) => (art[k[1]] = article[k[0]], art), {})) });BTW your code is missing a closing}\$\endgroup\$ifis missing. That begs the question, is there other code missing? \$\endgroup\$