Mak_091
Mak_091

Reputation: 347

Object property getting blank in vue

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

Answers (3)

minuteMed
minuteMed

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

T. Short
T. Short

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

Prayog Paudel
Prayog Paudel

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

Related Questions