I faced with this challenge to assign array to another array such that the arrays won't be reactive on changes from one of the array.
So to achieve this I made a local copy of the same array and assigned one to another but I would love to do stuffs dynamically where I am having the reactive issues.
Below is what am trying to achieve
const ComponentA = {
data: function() {
return {
categories:[
{
name: 'Category 1',
series: [
{
name: 'Series 1',
value: 5
},
{
name: 'Series 2',
value: 5
}
]
},
{
name: 'Category 2',
series: [
{
name: 'Series 1',
value: 50
},
{
name: 'Series 2',
value: 56
}
]
}
],
tempCategories:[
{
name: 'Category 1',
series: [
{
name: 'Series 1',
value: 5
},
{
name: 'Series 2',
value: 5
}
]
},
{
name: 'Category 2',
series: [
{
name: 'Series 1',
value: 50
},
{
name: 'Series 2',
value: 56
}
]
}
]
}
},
methods: {
resetCategory() {
this.tempCategories.forEach((category,i)=>{
category.series.forEach((series,j)=>{
this.categories[i].series[j] = series;
});
});
}
}
}
after computations on categories i can reset the categories array with tempCategories by calling
this.resetCategory() and it works as expected.
Meanwhile I want to be able to do this assignment dynamically whereby when i have copy of the category array I can assign the array to both categories and tempCategories arrays, respectively and after computations with categories array i can reset the categories array with tempCategories array. So I did the following.
initialize(category) {
this.tempCategories = category;
this.categories = category;
}
I realize changes in this.categories reflects on this.tempCategories; I've even used the following options
initialize(category) {
this.tempCategories = category.slice();
//or this.tempCategories = Json.parse(Json.stringify(category));
this.categories = category.slice();
//or this.categories = Json.parse(Json.stringify(category));
}
yet the two arrays are still reactive. Please I need help on how to solve this problem.
initializefunction andthis.categories[i].series[j] = series;would still result in the same object existing in both arrays. I typically use_.cloneDeepfor stuff like this, though there are other methods. Just make sure you are always creating a deep copy. lodash.com/docs/4.17.15#cloneDeepArray.mapor.sliceto create an entirely new array. Try replacing theforEachparts with the above.mapcreate new array, but the object inside still reference to old obj, sonewArray[0].something = newThingwill change theoldArray[0]as well. I always use cloneDeep to make sure it is separated.