I am trying to call REST API and it's throwing error as below
[Show/hide message details.] TypeError: data.forEach is not a function
I am new to REST APIs.
My API structure looks like this
{
"Agents":
{
"@ZipCode": "33176",
"Agent": [
{
"AgencyID": "21",
"Name": "Anakarina Callejas",
"Phone": "305-515-5613",
"CityName": "KENDALL",
"Address": "10471 N Kendall Dr. #101. Miami, FL 33176",
"Reviews-Rating": "5",
"Reviews-Count": "74",
"image": "/images/agents/21.png"
},
{
"AgencyID": "116",
"Name": "Tamara Mourino",
"Phone": "305-256-0616",
"CityName": "PINECREST",
"Address": "12745 South Dixie Highway. #101. Pinecrest, FL 33156",
"Reviews-Rating": "5",
"Reviews-Count": "70",
"image": "/images/agents/116.png"
}]
}
}
amd my API call is like this
var request = new XMLHttpRequest();
request.open('GET', 'URL to the API', true);
request.onload = function () {
var data = JSON.parse(this.response);
data.forEach(agent => {
console.log(agent.Name);
});
}
request.send();
From Your API Structure it looks that your data
is an object
not an array
.
Firstly get the Agent array
from the data
object then iterate over it to get name
of each Agent
.
var responseData =JSON.parse(responseData);
var data= responseData.Agents.Agent;
data.forEach(agent => {
console.log(agent.Name);
});
Snippet with your sample Data:
var responseData='{"Agents":{"@ZipCode": "33176","Agent": [{"AgencyID": "21","Name": "Anakarina Callejas","Phone": "305-515-5613","CityName": "KENDALL","Address": "10471 N Kendall Dr. #101. Miami, FL 33176","Reviews-Rating": "5","Reviews-Count": "74","image": "/images/agents/21.png"},{"AgencyID": "116","Name": "Tamara Mourino","Phone": "305-256-0616","CityName": "PINECREST","Address": "12745 South Dixie Highway. #101. Pinecrest, FL 33156","Reviews-Rating": "5","Reviews-Count": "70","image": "/images/agents/116.png"}]}}'; var responseData =JSON.parse(responseData); var data= responseData.Agents.Agent; data.forEach(agent => { console.log(agent.Name); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.