Reputation: 39
Giving the following response:
response=[{"long":"long_value1","lat":"lat_value1","ts":"ts_value"},{"long":"long_value2","lat":"lat_value2","ts":"ts_value"},{"long":"long_value3","lat":"lat_value3","ts":"ts_value"},{"long":"long_value4","lat":"lat_value4","ts":"ts_value"}]
Then Using an api, I tried next step to do this operation in order to insert "address" property in response:
for(var i in response){
$http.get(url(i)).success(function(response2){
response[i].address = response2.valueToassign;
});
}
My problem is that the "address" property is inserted only in the last object like this:
response=[{"long":"long_value1","lat":"lat_value1","ts":"ts_value"},{"long":"long_value2","lat":"lat_value2","ts":"ts_value"},{"long":"long_value3","lat":"lat_value3","ts":"ts_value"},{"long":"long_value4","lat":"lat_value4","ts":"ts_value", "address":"address_value4}]
How does this loop could insert "address" in each object of the array?
Upvotes: 1
Views: 70
Reputation: 1646
The problem with your code is that it is async,before loop executes
Try This
var responses = [{"long":"long_value1","lat":"lat_value1","ts":"ts_value"},{"long":"long_value2","lat":"lat_value2","ts":"ts_value"},{"long":"long_value3","lat":"lat_value3","ts":"ts_value"},{"long":"long_value4","lat":"lat_value4","ts":"ts_value"}]
function uploader(i){
if(i< responses.length)
{
$http.get(url).success(function(response2){
if(response2){
response[i].address = response2.valueToassign;
uploader(i+1)
}
else{
alert('resposnse output is blank');
uploader(i+1)
}
});
}
else{
console.log(response);
}
}
uploader(0)
Upvotes: 1