Reputation: 347
I am trying to implement filter method in Vue component.
I have below filter method:
filterHotels:function(){
var thisHotels = this.hotelRoomArr;
console.log(this.hotelRoomArr['107572']['rooms'])
//this outputs:
{__ob__: Observer}
3: (...)
__ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
get 3: ƒ reactiveGetter()
set 3: ƒ reactiveSetter(newVal)
__proto__: Object
thisHotels['107572']['rooms'] = {};
console.log(this.hotelRoomArr['107572']['rooms']);
//this outputs:
{__ob__: Observer}
__ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
__proto__: Object
}
As seen in above code:
Though I am setting rooms property of thisHotels to blank object, rooms property of this.hotelRoomArr also getting changed.
Logically rooms property of this.hotelRoomArr should not get changed.
What I have to do so that this.hotelRoomArr won't get changed?
Upvotes: 0
Views: 392
Reputation: 887
its because when you do this var thisHotels = this.hotelRoomArr;
thisHotels
becomes a reference to this.hotelRoomArr
, when you modify one, it modify the other.
if you want a non-reference copy of the object, you can do this:
let thisHotels = JSON.parse(JSON.stringify(this.hotelRoomArr))
I personnally use the JSON object way
Upvotes: 1
Reputation: 3614
When you do var thisHotels = this.hotelRoomArr;
, thisHotels
becomes a reference.
Try using the lodash
function cloneDeep
:
https://lodash.com/docs/4.17.15#cloneDeep
import cloneDeep from 'lodash/cloneDeep';
...
var thisHotels = cloneDeep(this.hotelRoomArr);
This will instead make a copy and prevent this.hotelRoomArr
from being affected by the changes
Upvotes: 2
Reputation: 11
When creating the local variable thisHotels, spread hotelRoomArr instead of equating it. That may solve the issue.
//top code
var thisHotels = [...this.hotelRoomArr]
//remaining code
PS: Better use let instead of var
Upvotes: 0