-3

We have an empty object:

var obj = {};

I would like to make a for loop which with each iteration adds a new obj = {value: i, next: i+1}

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Zyg
  • 27
  • 1
  • 2
  • 8

2 Answers2

0

Simply use an array of objects and for every iteration push this values on it:

var obj=[];
for(var i=1;i<10;i++){
    obj.push({value: i, next: i+1});
}

This is a DEMO Fiddle.

For each iteration give the obj.value and the obj.next, take a look at JavaScript Object Properties for futher information.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • I doesn't work because it keeps overwrite the obj.value and obj.next with a new value. – Zyg Jan 15 '15 at 09:35
  • Yes of course it doesn't, sorry but you have to use an array of objects instead, because an Object can't contain different values for the same property. Take a look at my EDIT. – cнŝdk Jan 15 '15 at 09:46
  • first, your answer is incorrect - you forgot to `obj.push(newobj)` to array. Second, no need to create variable: `array.push({value: i, next: i+1});` – Kirill Pisarev Jan 15 '15 at 09:52
  • @chsdk this is not JSON, this is js object, so it's not necessary to use quotes in key names. – Kirill Pisarev Jan 15 '15 at 10:03
  • @chsdk i don't see the difference between results in both cases. [See](http://stackoverflow.com/questions/8294088/javascript-object-vs-json) – Kirill Pisarev Jan 15 '15 at 10:20
  • @KirillPisarev yes you are right, I just had a little confusion. Thanks anyway I will just Delete the unecessary comments. – cнŝdk Jan 15 '15 at 10:33
  • @KirillPisarev: It's just a typo I missed it If you had a look at the fiddle you will notice that I have the.push(), and you are right about the newobj wich is not necessary. – cнŝdk Jan 15 '15 at 10:35
0

Not that sure what you mean but what about this

var obj = [];
function Obj(i){
    this.value = i;
    this.next = i+1;
}

for (var i= 0;i<10;i++){
    obj.push(new Obj(i));
}

Instead of an object of objects an array of them

znap026
  • 429
  • 1
  • 5
  • 15