-4

I an array like this

@observable data = [{a: 1}, {b: 1}, {c:1}];
 @observable sampleData = [];

I want to do a slice

 this.sampleData = this.data .slice(0, 1);
 this.sampleData[0].a = 2; 

I want "2" to effect the the record in "sampleData" not in the "data" array what is happening now.

chobo2
  • 83,322
  • 195
  • 530
  • 832

1 Answers1

-2

So you basically want to create a copy of every sliced element. You can do it like this:

this.sampleData = this.data.slice(0, 1).map(obj => ({ ...obj }))

Or using Object.assign:

this.sampleData = this.data.slice(0, 1).map(obj => Object.assign({}, obj))

Be advised that this is only a shallow copy, so if your object has nested structure, you would have to perform a deep copy instead.

pwolaq
  • 6,343
  • 19
  • 45