I've encountered an issue while attempting to loop through a JSON object to extract data. Whenever I run my code, I receive this error:
Type Error: element.listing.forEach is not a function.
It's worth mentioning that I've used this method earlier in my code, and it worked flawlessly. I tried the solutions provided on forEach is not a function error with JavaScript array, but none of them resolved the issue. Instead, the string ended up being filled with white spaces. Here's the snippet of my code:
var JSONBody = JSON.parse(body);
var dataString = "";
var count = 0;
//Get required data from response body:
JSONBody.forEach(function(element) {
if(element.listing != null){
element.listing.forEach(function (element2) {
dataString = dataString + element2.media[0].url;
dataString = dataString + "!!!";
dataString = dataString + element2.propertyDetails.bedrooms;
dataString = dataString + "!!!";
dataString = dataString + element2.propertyDetails.bathrooms;
dataString = dataString + "!!!";
dataString = dataString + element2.propertyDetails.carspaces;
dataString = dataString + "!!!";
dataString = dataString + element2.propertyDetails.displayableAddress;
dataString = dataString + "|||";
//console.log(element2.media[0].url);
count++;
}, this);
console.log(dataString);
}else{
dataString = "";
console.log("Listings is NULL!");
}
}, this);
JSONBody structure:
[ { type: 'PropertyListing',
listing:
{ listingType: 'Rent',
id: 11658083,
advertiser: [Object],
priceDetails: [Object],
media: [Array],
propertyDetails: [Object],
headline: 'Ultra Modern Furnished Apartment with Stunning Views',
summaryDescription: '<b>Ultra Modern Furnished Apartment with Stunning Views</b><br />Brisbane\'s newest luxury complex \'Spire\' hits the market with huge popularity. Apartment 2704 offers the lucky resident the very best of the already stunning facilities and views with 27t...',
hasFloorplan: false,
hasVideo: false,
labels: [Array],
inspectionSchedule: [Object],
listingSlug: '2704-550-queen-street-brisbane-city-qld-4000-11658083' } },...