1

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?

1
  • Look up async loops. Also, for ... in should not be used on arrays. Commented Mar 2, 2017 at 14:38

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I'm assuming you're trying to do this with recursion?
Yes Because your loop execute before your call is successed,Check my updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.