I am trying to loop through a JSON response from a Web API inside of the Fetch API. When I do a console log I am getting the following JSON string from the Web API response
However, when I try to loop through this response using the forEach loop it says that data.forEach is not a function. I tried using JSON.parse but that also failed. the following is my fetch api code.
Since you are returning a string that happens to be formatted as a JSON array (a list of dictionaries), but it’s still just a string until you parse it.
For that matter, save your code the lookup time and predefine your target element, rather than querySelector-ing the same element multiple times inside a loop.
Thank you everyone for your replies. This line const arrayObject = JSON.parse(data.data) arrayObject.forEach(file => { is the one that did the trick. I previously tried using JSON parse inline without setting it to a variable but it didn’t work.
Normally I would predefine my target elements but this is a special use case where I get the names and paths of all images from the image folder in the web server to populate a popup on a webpage. Then the user can select any image in the popup to be the source of any existing image on the web page. Of course I will then need to update the page source on the server to make this change permanent. I can also optimize the code by caching the api data.