0

I've got a quite strange js question. I've got a Vue component (but I think Vue is not important here). It has a data property called current_query. On a method that responds to an event, I want to modify that property. Using Lodash here. And there's a really curious behaviour. Say this.current_query is initially == { test: 500 }. Say also that 'field' parameter is 'test'. By 'unsetting' it from current_query, in fact I'll empty current_query itself. Perfect. Thing is, that (only) when using unset, if I log current_query before calling unset, I'll get an empty object. How is it possible?

  on_applied_option_click(field){
    console.log(this.current_query); // gives { test: 500 } (OK)
  }, // end click

  on_applied_option_click(field){
    console.log(this.current_query); // gives empty object only if, and when, using _.unset  (??)
    _.unset(this.current_query, field);
    console.log(this.current_query); // gives empty object as well  (OK)
  }, // end click

I've found out that if I use _.omit instead, it all goes fine:

  on_applied_option_click(field){
    console.log(this.current_query); // gives { test: 500 }  (OK)
    this.current_query = _.omit(this.current_query, field);
    console.log(this.current_query); // gives empty object, which at this point is fine
  }, // end click

Why? The only thing I can say is that _.unset mutates the objects while _.omit creates new ones. But still, I think it's quite impossible that _.unset is going to mutate the object before even getting called (???). Never seen a thing like this. Has anyone some good explanation of this strange behaviour?

Luca Reghellin
  • 7,426
  • 12
  • 73
  • 118

1 Answers1

1

Instead of doing console.log(this.current_query), try console.log(JSON.stringify(this.current_query)). That logs reliably the state of this.currenty_query at the time of logging, and not possibly some state afterwards.

And that should solve the confusion.

Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33