2017-08-03 53 views
1

我有这个来自Google地图的JSON响应,保存为.json文件。这是对附近学校的搜索。通过Json循环并追加到对象

我只想提取学校的名称和位置,并将它们保存到elemSchoolsArr变量中供以后使用。

我不知道为什么我下面的代码没有循环通过json响应,检查elemSchoolsObj只显示一个对象,而不是10,我想稍后推送到elemSchoolsArr

var elemSchoolsArr = []; 
var elemSchoolsObj = {}; 

$.getJSON('elementary-schools.json', function(data){ 
    for (var i = 0; i < 10; i++) { 
    elemSchoolsObj.title = data.results[i].name; 
    elemSchoolsObj.location = data.results[i].geometry.location; 

    } 
}); 

elemSchoolsArr.push(elemSchoolsObj); 

回答

0

您只需将对象推入循环内部的数组,以便每个对象都被推入,而不仅仅是一个。很明显,这段代码实际上并不会运行,因为我们没有在这里获得你的JSON。

var elemSchoolsArr = []; 
 

 
$.getJSON('elementary-schools.json', function(data){ 
 
    for (var i = 0; i < 10; i++) { 
 
    var elemSchoolsObj = {}; 
 
    elemSchoolsObj.title = data.results[i].name; 
 
    elemSchoolsObj.location = data.results[i].geometry.location; 
 
    elemSchoolsArr.push(elemSchoolsObj); 
 
    } 
 
});

这里有一个功能例如...

var array = ["a", "b", "c", "d", "e"]; 
 
var first_try = []; 
 
var second_try = []; 
 

 
for(var i = 0; i < array.length; i++){ 
 
    // we define our object in the loop but don't add it to the array 
 
    var obj = { 
 
    \t item: array[i] 
 
    }; 
 
} 
 

 
// we push one object in to the array 
 
first_try.push(obj); 
 

 
// we get one object in the array 
 
console.log(first_try); 
 

 
for(var i = 0; i < array.length; i++){ 
 
    // we define our object in the loop 
 
    var obj = { 
 
    \t item: array[i] 
 
    }; 
 
    // we push each object we define in the loop in to the array 
 
\t second_try.push(obj); 
 
} 
 

 
// we get all the objects in the array 
 
console.log(second_try);

+0

太谢谢你了。您的解决方案完美运作 – CryptoPsyche

+0

很高兴我能帮忙:) – sauntimo