Difficulty in modifying an object's property/value using a variable within a function

VueJS is the framework I am currently working with and I am attempting to utilize v-model to link checkboxes to values stored within an object:

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

Here is the checkbox element setup:

<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>

The function filterJobs() is triggered each time I click on one of these checkboxes:

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 result: The function takes in "j" which represents the string "Baker". The syntax for modifying an object's property functions correctly, pushing "Baker" to the filters.jobs array, and setting filters.jobsChecked.j to make filters.jobsChecked.Baker = true

Actual result: The function interprets "j" as the string "Baker", adds "Baker" to the filters.jobs array, but incorrectly adds the key/value pair 'j: true' to filters.jobsChecked.

I am puzzled because the function seems to understand that 'j' is actually a variable with the value of "Baker", so it should recognize that "filters.jobsChecked.j" = "filters.jobsChecked.Baker" and update the value to true using object modification syntax.

I have researched extensively about this issue but have not found a clear explanation. Based on my understanding, I am implementing it correctly and utilizing [] square brackets since it is a variable being passed in. I also attempted ['j'] but this simply added the key value "j: false" to the object...

What am I overlooking? I suspect it might be something incredibly obvious...

Answer №1

An error is occurring due to the incorrect syntax used to access the string within the variable j in relation to an object property.

The code filters.jobsChecked.j is attempting to find a property named "j" within the jobsChecked object, which is not present. To correctly evaluate j as a variable, use bracket notation:

filters.jobsChecked[j]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortless navigation with smooth scrolling on anchor links in react/next.js

Can smooth scrolling be achieved using only CSS when clicking on an anchor link within a react component? ... render( <a href="#smooth-link">Link To There</a> .... <div id="smooth-link"> .... ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Issue: Attempting to access the property 'then' of an undefined entity causes a TypeError. However, the code executes

Here's an unusual situation. I am working with Vue.js connected to a php backend, and I have the following code snippet: validateEmail(){ if(!this.emailModel.loading && this.$refs.emailForm.validate()) ...

Struggling to find the right strategy for obtaining real-time data while implementing customized filters

After spending a week scratching my head and experimenting with different approaches, I'm hoping to find some help here... I am working on an application that needs to provide real-time data to the client. I initially considered using Server-Sent-Eve ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

How to extract information for divs with specific attribute values using Jquery

I have multiple divs with IDs like #result-1, #result-2, each followed by a prefix number. To count the number of list items within these divs, I use the following code: $(document).ready(function () { var colorCount = $('#result-1 .item-result ...

Experiencing a lack of information when trying to retrieve data through an http request in an express/react

Issue: My problem lies in attempting to retrieve data from http://localhost:3000/auth/sendUserData using the http protocol. Unfortunately, I am not receiving any data or response, as indicated by the absence of console logs. Tools at my disposal: The te ...

Dynamically divide canvas screens based on fabricjs dropdown selection

I am attempting to implement split screens in fabric js, such as 1, 2, 4, 8, and 16. The screen should split based on the selection from the dropdown menu. Check out my current code where I have successfully uploaded images. If I click on the images, th ...

applying conditional rendering in vue.js

I'm currently working on developing a chat application using the guidelines outlined in this tutorial: https://socket.io/get-started/private-messaging-part-1/ One of my goals is to customize the appearance of the messages, so that when a message is s ...

Trouble initiating Jquery on a dynamically generated table

I am currently working on a project in ASP.Net where I need to dynamically build an HTML Table. I have implemented the ability for users to resequence rows in the table, but I'm facing issues with the delegate events I've written. Sometimes they ...

What kind of data does this collection hold, and what is the best method to retrieve its stored values?

I recently received a code to program a logic for and I have successfully figured out my algorithm. However, I am facing difficulty determining the datatype of a particular declaration. My task involves comparing the values of "skills" in each row to &apos ...

What is the correct way to send an HTTP error code to an error handling middleware?

Currently, I am in the process of developing a RESTful API using node.js and express framework. I would like to create a single error handling middleware for this project. The approach I am currently considering involves: router.get('/some-resource&a ...

Controlled Checkbox Component in React

I'm really struggling with this. While I can easily work with select drop downs and text fields, I just can't seem to get checkboxes to function properly in a controlled manner. I want them to 'toggle' and respond to events in a parent ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

Phantom.js: Exploring the Power of setTimeout

Below is a snippet of code that intends for Phantom.js to load a page, click on a button, and then wait for 5 seconds before returning the HTML code of the page. Issue: Utilizing setTimeout() to introduce a delay of 5 seconds leads to the page.evaluate fu ...

Is there a way to modify page URLs without causing a refresh, regardless of browser?

Despite my extensive searches on various online platforms, including stackoverflow, I have yet to come across a satisfactory answer to my question. While I find the window.history.pushState() and window.history.replaceState() methods quite user-friendly, ...

Transform a pandas DataFrame into a two-tiered nested JSON structure by utilizing the groupby function

Let's say there is a pandas dataframe named df with the following structure: source tables src1 table1 src1 table2 src1 table3 src2 table1 src2 table2 Currently, I have a code s ...

Looking to implement the v-model with a bootstrap-vue b-form-radio on a webpage? Here's how you can

bootstrap-vue When the server side sends me the N categories for radio button groups in JSON format, users will be prompted to rate each category as a priority - high, medium, or low. I need to dynamically generate radio button groups for each category to ...

A clever JavaScript function generator encapsulated within an instant function nested within a jQuery ready statement

This code snippet features an immediate function enclosed within a jQuery ready function. $((function(_this) { return function() { document.write('called!'); }; })(this)); I am puzzled by where the resultant function ...