Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a value inside an object variable

I have the following.

var dataset = {val1 : 0, val2 : 0, val3 : 0};
var person = [];
var totalPeople = 10;

for(var i = 0; i <totalPeople; i++) {
   person[i] = dataset; 
}

Why i chose this approach, click here .

I'm trying to make one of the values auto increment inside another for loop.

I've tried the following approaches to no avail.

person[1]{val1 : 0,
          val2 : 0,
          val3 : val3 + 1};

person[1]{val1 : 0,
          val2 : 0,
          val3 : person[1].val3 + 1};

person[1].val3 = person[1].val3 + 1;

any ideas?

like image 208
Swift Avatar asked Sep 16 '14 19:09

Swift


3 Answers

This should be the right:

person[1].val3 += 1;
like image 147
reyaner Avatar answered Oct 05 '22 23:10

reyaner


This should work.

var dataset = {val1 : 0, val2 : 0, val3 : 0};
var person = [];
var totalPeople = 10;

for(var i = 0; i <totalPeople; i++) {
   dataset[i].val3 ++; 
}

Could you explain more what you are trying to achieve?

like image 24
Santiago Nicolas Roca Avatar answered Oct 06 '22 01:10

Santiago Nicolas Roca


Totally sorry. The solution that you're referring to here was posted by me and is incorrect. I just updated my answer in that post.


Don't use the array initialization style that I originally posted:

var dataset = {val1 : 0, val2 : 0, val3 : 0};
var person = [];
var totalPeople = 10;

for(var i = 0; i < totalPeople; i++) {
  person[i] = dataset; // this assigns the *same* object reference to every 
                       // member of the person array.

}


This is the correct way to initialize your person array:

var person = [];
var totalPeople = 10;

for(var i = 0; i < totalPeople; i++) {
  person[i] = {val1 : 0, val2 : 0, val3 : 0}; // do this to create a *unique* object 
                                              // for every person array element
}


If you use the correct array initializtion shown directly above, then you can increment val3 like this with each loop iteration:

var person = [];
var totalPeople = 10;

for(var i = 0; i < totalPeople; i++) {
  person[i] = {val1 : 0, val2 : 0, val3 : 0};
  person[i]['val3'] = i;
}


Sorry again for the bad information that I provided in the other post. (All other info is correct. Just the array initialization code was bad.) I hope this updated information helps.

like image 43
Gerald LeRoy Avatar answered Oct 05 '22 23:10

Gerald LeRoy