My goal is to iterate through an array of results and do stuff with the data but for some reason I can’t get the foreach loop in javascript to work, I can’t seem to make any sort of enumeration work.
Here’s my test
console.debug("I got this far.");
for(var i=0;i< results.length; i++){
console.debug("Worked.");
}
console.debug("Past.");
console.debug(results);
I have also tried
results.forEach(function(x) { console.debug("Worked"); });
and
for(var x in results)
None seem to be working, is there something I’m doing wrong?
The output for the above is
I got this far. query.html:39
Past. query.html:40
[ Object , Object , Object , Object , Object , Object , Object , Object , Object , Object ]
So I know that the results variable is the right type but it is just not iterating. There is another place where the forEach() works just fine but here it’s not, any suggestions on how to debug and address this would be helpful.
full code (WORKING SOLUTION)
var table;
var request = { query : { match_all : {}}};
var map;
function initialize(results) {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(41.4, -71.3),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
results.forEach(function(x) {
var markerLoc = new google.maps.LatLng(x.location.lat, x.location.lon);
var marker = new google.maps.Marker({
position: markerLoc,
map: map,
title: "Hello World!"
});
});
};
$(document).ready(function() {
var results = [];
$.ajax({
url: "http://localhost:9200/devices/devices/_search",
type: "POST",
data: JSON.stringify(request),
dataType: "json",
beforeSend: function(x) {
if ( x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(data) {
data.hits.hits.forEach(function(x) { results.push(x._source); } );
initialize(results);
}
});
});
You are passing
resultstoinitializeas soon as the Ajax request has been sent. You aren’t waiting for the response to come back, so the code that populates it doesn’t fire until too late.Move the call to
initializeso it is inside thesuccesshandler.