我只将最后一个元素添加到JS数组中

时间:2014-09-11 10:28:05

标签: javascript arrays json data-objects

到目前为止,这是我的代码:我正在尝试使用GAJSON对象的属性创建一个名为dataJSON的新JSON对象。但是,当我尝试迭代GAJSOn对象时,我只将其最后一个元素添加到数组中。

 var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":
 "3","country":"Spain"},{"bounceRate":"6","country":"Romania"},
 {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},  
 {"bounceRate":"2","country":"Norway"}]}';
 var GAJSON=JSON.parse(GAstring);
 var viewJSON = {
    data:[]
 };
 var dataJSON ={};
 for(var i =0; i<GAJSON.data.length; i++) {
     dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;
     dataJSON["country"] = GAJSON.data[i].country;
 }
 viewJSON.data.push(dataJSON);

2 个答案:

答案 0 :(得分:2)

你的push新对象应该在循环中。

 for(var i =0; i<GAJSON.data.length; i++) {
   viewJSON.data.push({
     bounceRate: GAJSON.data[i].bounceRate,
     country: GAJSON.data[i].country
   });
 }

DEMO

答案 1 :(得分:1)

每次dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;

时,您都会覆盖值

试试这段代码:

var GAstring ='{"data":[{"bounceRate": "4","country":"Denmark"},{"bounceRate":"3","country":"Spain"},{"bounceRate":"6","country":"Romania"},     {"bounceRate":"1","country":"Bulgaria"},{"bounceRate":"0","country":"Lithuania"},     {"bounceRate":"2","country":"Norway"}]}';
 var GAJSON=JSON.parse(GAstring);
 var viewJSON = {
    data:[]
 };
 var dataJSON ={};
 for(var i =0; i<GAJSON.data.length; i++) {
     dataJSON[i] = [];
     dataJSON[i]["bounceRate"] = GAJSON.data[i].bounceRate;
     dataJSON[i]["country"] = GAJSON.data[i].country;
 }
 viewJSON.data.push(dataJSON);
console.log(viewJSON);

DEMO