0

I'm getting very weird result if I want to remove matched elements of object of arrays

The code snippet is here;

computed;

...mapGetters('accounts', ['accounts'])  

info: this.accounts setted with mapAction in created() and it's an array and length is 6

methods;

     assignEvent(teammate){

      this.pickAccounts = this.accounts;

      this.pickAccounts.splice(0, 1)

      this.assign.teammate = teammate;
      this.show.assign = true;

    }

step 1 - assignEvent() fired then this.pickAccounts.length reduced from 6 to 5

it's ok but;

step 2 - Let's Trigger assignEvent() again I assume that going to be same thing again 6 to 5 because I assume that If I set;

this.pickAccounts = this.accounts;

this.pickAccounts going to be equal to this.accounts but it's not.

If I trigger this function (assignEvent()) this.accounts is also changing.

How this.accounts is changing? I'm getting this.accounts from vuex store I'm not changing it's value it must be stay same...

Erdi
  • 1,824
  • 3
  • 21
  • 31
  • 1
    try `Object.assign(this.pickAccounts , this.accounts);` – Boussadjra Brahim Jan 23 '19 at 00:53
  • Also, `...mapGetters('accounts', ['accounts'])` should be `...mapGetters(['accounts'])` – ljubadr Jan 23 '19 at 00:55
  • 2
    Also, use `this.pickAccounts = this.accounts.slice(0)` to clone the `this.accounts` array. Your approach is assigning `this.accounts` by reference to `this.pickAccounts`, so when you change `accounts` or `pickAccounts` with `splice(0, 1)`, it changes both. – ljubadr Jan 23 '19 at 00:58
  • How Can I avoid this updating of this .accounts? I want to get constant data everytime from this.accounts! I don't want to manipulate it – Erdi Jan 23 '19 at 01:04
  • 1
    `this.pickAccounts = this.accounts.slice(0)`. Note `slice(0)` – ljubadr Jan 23 '19 at 01:08
  • ```this.pickAccounts = Object.assign(this.pickAccounts, this.accounts);``` worked! – Erdi Jan 23 '19 at 01:10
  • I would still use `.slice(0)` instead of `Object.assign()`. While second one works, it can have some side-effects. Check [this answer](https://stackoverflow.com/questions/53342174/why-object-assign-works-with-an-array) – ljubadr Jan 23 '19 at 01:29

0 Answers0