I am trying to turn a for
loop into a forEach
loop, but it doesn't seem to be working...
Here is my code:
const townDataURL = "[some link I probably can't disclose...]"
const towns2get = [
"Preston",
"Fish Haven",
"Soda Springs"
]
fetch(townDataURL)
.then((response) => {
return response.json()
})
.then((jsonData) => {
const towns = jsonData["towns"].filter((item) => {
// for (let i = 0; i<towns2get.length; i++) {
// if (item.name == towns2get[i]) {
// return item
// }
// }
return (towns2get.forEach(elem => {
return ( (item.name == elem) ? (item) : "Hello?" )
}))
})
console.log(towns)
})
When I have the commented code run it gives me this:
(3) [{…}, {…}, {…}]
0: {name: "Fish Haven", photo: "fishhaven.jpg", motto: "This is Fish Heaven.", yearFounded: 1864, currentPopulation: 501, …}
1: {name: "Preston", photo: "preston.jpg", motto: "Home of Napoleon Dynamite.", yearFounded: 1866, currentPopulation: 5204, …}
2: {name: "Soda Springs", photo: "sodasprings.jpg", motto: "Historic Oregon Trail Oasis. The Soda is on Us.", yearFounded: 1858, currentPopulation: 2985, …}
length: 3
__proto__: Array(0)
Which is exactly what I want, but I want to simplify my code... what I have now gives me this:
[]
length: 0
__proto__: Array(0)
I've done some debugging and I know that my conditional statement with the ternary operator works fine, and it is returning a value... but I can't seem to figure out why it isn't returning it back to the filter
method...
Does it not work this way? Or do I have to somehow put the forEach
with the filter
?
Thank you for any help!