Object array in Typescript when changing a value the others are changed

Asked

Viewed 591 times

0

I have this class in Typescript

export class PageModel {

  constructor () {
  }

  Name: string;
  Content: string;
  Url: string;

}

And created an array of this class

let test: PageModel[];
test = new Array(21);
test.fill(new PageModel());
test.fill(new PageModel());

I set this array with two instances:

test[0].Content = 'Firt instatance';
test[1].Content = 'Second instatance' ;
console.log (test[0].Content + test[1].Content);

But in the console is shown 'Second instance Second instance'

The second value exceeds the first value.

Is there any way to solve this problem?

1 answer

1


See the documentation of Array.prototye.fill:

The method fill() fills all array values from the initial index to a final index with a static value.

That is, all positions of your array will be exactly the same instance and by modifying it in one of the indexes, the change will be reflected in all others. As you have already started the array with 21 positions, you don’t need to use the fill(), simply assign the instance to the desired index:

test[0] = new PageModel();
test[1] = new PageModel();

Or, if you don’t want to initialize one by one, you can use the fill to boot them all with undefined and map them to a new instance of the class you want:

test = new Array(21).fill().map(it => new PageModel());

Example:

class PageModel {}

const test = new Array(5).fill().map(it => new PageModel())

test[0].name = 'foo'
test[1].name = 'bar'

console.log(test);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.