循环通过Json并附加到对象

时间:2017-08-03 00:24:29

标签: javascript jquery 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);

1 个答案:

答案 0 :(得分:0)

您只需要将对象推入循环内部的数组中,以便每个对象都被推入,而不是仅仅一个。显然,此代码段实际上并未运行,因为我们未在此处获取您的JSON。

&#13;
&#13;
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);
  }
});
&#13;
&#13;
&#13;

这是一个功能性的例子......

&#13;
&#13;
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 = {
  	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 = {
  	item: array[i]
  };
  // we push each object we define in the loop in to the array
	second_try.push( obj );
}

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