Reputation: 93
I have an array list like this
private options: Array<any> = [];
private optionsListDuplicate: Array<any> = [];
let data=[{id:"id",name :"name"},{id:"id2",name:"name"}];
for(let i=0;i<data.length;i++){
this.options.push({
label:data[i].name,
value:data[i].id
});
this.optionsListDuplicate.push({
label:data[i].name,
value:data[i].id
});
}
but when i modify the options
array object, it modifies optionsListDuplicate
object as well. Please help me understand why that happens.
I am adding a new list to the existing options object like this
this.options.push({
label:"somelabel",
value:"someid"
});
I have the requirement that I need to retain the original object. So i did this
this.options=this.optionsListDuplicate;
but this.optionsListDuplicate
is having the modified array object
Upvotes: 0
Views: 129
Reputation: 18312
Well, if your assigning one array to the other, then of course when you modify one, you modify the other.
When you do
this.options = this.optionsListDuplicate;
You aren't copying the array, just creating a new variable that points to it. In fact, by doing this, the old array pointed to by this.optionsListDuplicate
is lost. I suggest you to read about reference and value types in JavaScript: Primitive value vs Reference value
If you want to keep the original array, then you must do:
this.optionsListDuplicate = this.options.slice();
As, by your code (you are adding elements to this.options
) I understand that you want this.optionsListDuplicate
to be the 'original' array.
Of course, now you don't need to initialise both arrays in the for
statement. In fact, you don't need for
for anything, it's better if you use map
:
private options: Array<any>;
private optionsListDuplicate;
let data=[{id:"id",name :"name"},{id:"id2",name:"name"}];
this.options = data.map(item => { label: item.name, value: item.id });
this.optionsListDuplicate = this.options.slice();
Upvotes: 0
Reputation: 3176
There are 2 types of copies
When you perform a shallow copy, (i,e) something like x = y
, x and y refer to the same memory location, so when you change either x
or y
, the change will be reflected in both the variables.
Example
let x = [1, 2, 3]
let y = x;
let z = x.slice(); // or JSON.parse(JSON.stringify(x));
x.push(4);
console.log(y); // prints [1, 2, 3, 4]
console.log(z); // prints [1, 2, 3]
To perform a deep copy, you can use the splice
method in case of an array or JSON.parse(JSON.stringify(x))
in the case of objects.
When a deep copy is performed, the changes in one variable will NOT affect the others.
but when i modify options array object, it is modifying optionsListDuplicate object as well
In your case, you might be using the following somewhere
this.optionsListDuplicate = this.options;
Change it to
this.optionsListDuplicate = this.options.slice();
// or..
this.optionsListDuplicate = JSON.parse(JSON.stringify(this.options));
Upvotes: 0