简体   繁体   中英

Trouble changing object property/value via variable in function

I am using VueJS and trying to use v-model. to connect checkboxes to values in an object:

jobsChecked: {Baker: false, Cook: false, Miner: false}  // etc...

and the checkbox element:

<div class="checkbox jobs" v-for="j in jobs" :key="j">
  <label>
    <input type="checkbox" v-model="filters.jobsChecked.j"
    @change="filterJobs(j)"> {{ j }}
  </label>
</div>

with filterJobs() firing when I click one of these boxes:

filterJobs(j) {
  if (!this.filters.jobs.includes(j)) {
    this.filters.jobs.push(j);
    this.filters.jobsChecked[j] = true;
  } else {
    const index = (ele) => ele === j;
    const remove = this.filters.jobs.findIndex(index);
    this.filters.jobs.splice(remove, 1);
    this.filters.jobsChecked[j] = false;
  }
  console.log("jobs filters: ", this.filters.jobs);
  console.log("jobs checked: ", this.filters.jobsChecked);
}

Expected output : The function receives "j" which is read as the string "Baker". The syntax for modifying an Object's property works and checking "Baker" pushes Baker to the filters.jobs array AND uses filters.jobsChecked.j to make filters.jobsChecked.Baker = true

Actual output : The function receives "j" which is read as the string "Baker", pushes "Baker" into the filters.jobs array, but then adds the key/value 'j: true' to filters.jobsChecked.

My confusion comes in here where I am expecting that, since the rest of the function seems to be fully aware the 'j' is not actually the letter j, but instead a passed variable with the value of "Baker", it will know that "filters.jobsChecked.j" = "filters.jobsChecked.Baker" and using object modification syntax, it should change the value to true as I wrote.

I have been reading other posts and websites all night about this and nothing I found made any sense or seemed to englighten me on this situation. As far as I can see, I am writing it exactly as it should be and using [] square notation since it's a variable being passed in. I also tried writing ['j'] but that also just ADDED the key value "j: false" to the object...

What am I missing here? I have a feeling it's something stupidly obvious...

There is invalid syntax for accessing the string contained in j in the context of an object property.

filters.jobsChecked.j is looking for a property named "j" on the jobsChecked object, but it doesn't exist. Use bracket notation to evaluate j as a variable:

filters.jobsChecked[j]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM