Reputation: 43
I need help with the forEach method. I am trying to mess around with the Pokemon API, but I can't run a forEach method without it returning undefined.
When I tried to use forEach instead of the map (I noticed map returned one big array) it still returned undefined.
fetch('https://pokeapi.co/api/v2/pokemon?limit=151')
.then(res => res.json())
.then(data => fetchPokemon(data))
const fetchPokemon = (res) => {
console.log(res)
// This turns the object api into an array
const arr = [res];
console.log(arr)
// This creates a variable to map correctly
const firstArr = arr[0].results
// This creates a new array with pokemon name
const array = firstArr.map(pokemon => pokemon.name)
console.log(array);
const html =
`
<div>${array}</div>
`
const pokemon = document.querySelector('.pokemon');
pokemon.innerHTML = html;
}
Upvotes: 1
Views: 383
Reputation: 568
The forEach() method calls a function once for each element in an array, in order.
forEach
: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database)
map
: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase)
from here
Meaning, if you want to do something for every element of the array, foreach is the correct function.
Example of Array.ForEach
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
Now, you are trying to create a new array with all the pokemon names, therefore map is correct - you are mapping the array into a new array.
However, if you want to, say, make an li element in html for every name, then it would be correct to use ForEach.
Example:
fetch('https://pokeapi.co/api/v2/pokemon?limit=151')
.then(res => res.json())
.then(data => fetchPokemon(data))
const fetchPokemon = (res) => {
const firstArr = [res][0].results
var ul = document.getElementById("pokemon");
firstArr.forEach(function (entry) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(entry.name));
ul.appendChild(li);
});
}
<ul id="pokemon"></ul>
Upvotes: 1
Reputation: 2976
So there's a few things going on:
axios('https://pokeapi.co/api/v2/pokemon?limit=151')
.then(({data}) => fetchPokemon(data))
const fetchPokemon = (res) => {
//extract the results property into its own variable
const {results} = res;
//create an array of just object.name properties
const names = results.map( pokemon => pokemon.name)
}
Upvotes: 1