如何在数组的对象中插入元素

时间:2017-03-02 14:34:01

标签: javascript angularjs arrays

给出以下回复:

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"}]

然后使用api,我尝试了下一步来执行此操作,以便插入"地址"财产回应:

    for(var i in response){
      $http.get(url(i)).success(function(response2){
        response[i].address = response2.valueToassign;        
                });
}

我的问题是"地址" property仅在最后一个对象中插入,如下所示:

 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}]

此循环如何插入"地址"在数组的每个对象中?

1 个答案:

答案 0 :(得分:1)

代码的问题在于它在循环执行之前是异步的 试试这个

        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)