遍历JSON对象

遍历JSON对象

问题描述:

我有这样的遍历JSON对象

var Obj = { 
    'id1': 'abc', 
    'id2': 'pqr', 
    'id3': 'xyz' 
} 

一个JSON对象,我打电话异步方法,而迭代,这样

var otherObj = {}; 
for (i in Obj) { 

    var someData = Obj[i]; 

    File.upload(someData).then(function(response) { 
     otherObj[i] = response.data.url; 
    }); 
} 

但在这我越来越otherObj为

otherObj = { 
    'id3':'url1', 
    'id3':'url2', 
    'id3':'url3', 
} 

所以我的问题是什么是最好的方式正确关联每个关键目前在Obj对象与回应File.upload()

+0

看看http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – RafaelC

你需要使用一个IIFE

for (i in Obj) { 

    var someData = Obj[i]; 
    (function(i) { 
     File.upload(someData).then(function(response) { 
      otherObj[i] = response.data.url; 
     }); 
    })(i); 
} 

这将在回调File.upload().then的执行上下文保存i。之前发生的事情是每个File.upload().then'看到'最后迭代的i这是所有回调可见。