How do I do this?

How do I work on a property(array) inside an object, without modifying the array; something like this:


var State = function(state) {
  this.state = state;
}
var index  = [0,1,2];
var newState = new State(["E", "E", "E"]);
index.forEach(function(pos) {
  newState.state[pos] = pos;
  console.log(newState.state);
});

output:  
[0, "E", "E"]
[0, 1, "E"]
[0, 1, 2]
but what I want is:
[0, "E", "E"]
["E", 1, "E"]
["E", "E", 2]

Hey, you are declaring newState before the forEach therefore it is storing the previous value each time. If instead you move the newState declaration to inside the forEach it will create a new array each time as you requested:

var State = function(state) {
  this.state = state;
}
var index  = [0,1,2];

index.forEach(function(pos) {
  var newState = new State(["E", "E", "E"]);
  newState.state[pos] = pos;
  console.log(newState.state);
});

More generally, if you want to work on an array inside an object without modifying it, then you can simply call .slice() on the array. For example:

var State = function() {
  this.array1 = [1,2,3];

}
var newState = new State;
var arr1 = newState.array1.slice() // now array1 will not be modified if you use arr1
2 Likes

If you want a copy of an array, you can also use the cool new spread operator in ES6 ā€¦

var arr1 = [ ...newState.array1 ];

Iā€™m a fan of the new syntax.

MDN Spread Operator

Of course, as with .slice() if there are any objects referenced in the array elements, you will not be copying those, merely pointing to them in the new array.

3 Likes

thanks for both of your help

1 Like