0

Here is my code so far: I am trying to create a new JSON object called dataJSON using properties from the GAJSON object. However, when I try to iterate over the GAJSOn object, I get only its last element to be added to the array.

 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
  • Sure. You keep writing to the same properties of the dataJSON object over and over. What result were you expecting? Commented Sep 11, 2014 at 10:31
  • If you wanted an Array of objects, then create a new object inside the loop, and also .push() it inside the loop. Commented Sep 11, 2014 at 10:33

2 Answers 2

2

Your push of the new object should be within the loop.

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

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

You are overwriting values every time at dataJSON["bounceRate"] = GAJSON.data[i].bounceRate;

Try this code:

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

2 Comments

Why are you creating an array within an object within an array? Your code makes no sense - that's why you're downvoted.
@andy you are correct. But i was pointing error of OP. Your solution is best then me. +1 for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.