-1

I have strange issue, which I don't understand. I would like to make a JSON Object in JavaScript. My example code:

$(document).ready(function(){

var myJson = new Object();
var data = new Object();
myJson.items = [];

data.name  = 'test';

for (i = 0; i < 5; i++){
  data.counter = i;
  myJson.items.push(data);  
}
console.log(JSON.stringify(myJson));

});

Output:

{"items":[{"name":"test","counter":4},{"name":"test","counter":4},{"name":"test","counter":4},{"name":"test","counter":4},{"name":"test","counter":4}]}

Why the counter variable in JSON have always value 4 ??????

1
  • The property you're changing is always the same data.counter. Commented Nov 9, 2016 at 8:15

2 Answers 2

4

You are always working on the same data object
instead try putting data object initialization in loop

var myJson = new Object();

myJson.items = [];



for (i = 0; i < 5; i++){
  var data = new Object();
  data.name  = 'test';
  data.counter = i;
  myJson.items.push(data);  
}
console.log(JSON.stringify(myJson));

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

1 Comment

Construct objects, push them,to an array then JSON.stringify is also an option.
1

create a new object of var data = new Object(); inside for loop, comment the above one, also put data.name = 'test'; inside for loop

Comments

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.