0

I have a references problem that i can't handle with.

I have a array of strings. - ["String1","String1","String1"]

I am trying to map this array to have new array of objects { name: "String1", disabled: false } etc.

The code for that is:

   let teamsWithProperty = teams.map(team => {
      let object = {name: team, disabled: false}
      return Object.assign({},object)
   });

In next step i am creating an matrix of teamsWithPropery array:

    for (let i=0; i<numberOfRounds; i++){
      this.teamsMatrixForEachRound.push([...teamsWithProperty]);
    }

The problem is that when i am trying to change a objects value in for example [0][0] element of matrix all of first elements have changes propery

(this.teamsMatrixForEachRound[0][0]).name = "Example"

I want to change property only of first object in matrix; But im getting: enter image description here

dżejson
  • 11
  • 2
  • You initially only have `teamsWithProperty`, an array which contains 3 objects. When you try to copy the array with `this.teamsMatrixForEachRound.push([...teamsWithProperty]);`, although the array is copied, the objects are not. At the end of the loop, you still only have 3 objects in memory, so if one object gets mutated, all other objects at the same index will get mutated too. Consider creating `teamsMatrixForEachRound` with `Array.from` instead, see https://stackoverflow.com/a/51832006/ – CertainPerformance Oct 15 '19 at 00:19
  • Basically you have done -> `var a = {x: 1}; var b = [a,a,a]; b[0].x = 2; console.log(b);` If you copy this code and run it inside of the console, you might expect `"[{"x":2},{"x":1},{"x":1}]"`, but what you will get is `"[{"x":2},{"x":2},{"x":2}]"` If you can understand why that is, you will understand why your code does what it does. – Keith Oct 15 '19 at 00:38

0 Answers0