Employ a variable in order to send json

Is it possible to insert data into a predefined JSON variable using a variable? Here are the predefined JSON variables:

    data(){
        return {
            dataMON: [],
            dataTUE: [],
            dataWED: [],
            dataTHU: [],
            dataFRI: []

        }
    }

And this is the data that needs to be added:

getTimeTable() {
                var db = firebase.firestore();

                var date = new Date();
                var weekday = new Array(5);
                weekday[0] = "monday";
                weekday[1] = "tuesday";
                weekday[2] = "wednesday";
                weekday[3] = "thursday";
                weekday[4] = "friday";

                weekday.forEach(day => {

                    var dayLowerCase = day.slice(0, 3);
                    var dayUpperCase = dayLowerCase.toUpperCase();


                    var tmpTable = {
                        period: doc.id,
                        course: fullTempTable.fach,
                        teacher: fullTempTable.lehrer,
                        room: fullTempTable.raum
                                };
                                this.day.[dayUpperCase].push(tmpTable);   

                });
            }

The issue arises when trying to use day[dayUpperCase] as it searches for the object named dayUpperCase. Is it possible to utilize variables in this situation?

Answer №1

To retrieve the complete property name, you need to concatenate the full name in your string.

let monthUpperCase = monthLowerCase.toUpperCase();
let propertyName = "month" + monthUpperCase;

After that, you can retrieve it using bracket notation (without using a period in front):

this[propertyName]

Answer №2

It is considered best practice to establish a new object:

data() {
    return {
        day: {
            MON: [],
            TUE: [],
            WED: [],
            THU: [],
            FRI: []
        }
    };
}

This approach is more efficient in the long term compared to adding strings directly, as it maintains organization within your data object. Resorting to string concatenation for property names may indicate a potential "code smell" that suggests creating a separate object would be more appropriate. For instance, if another developer were to examine the data object, searching for "dataMON" using ctrl-f to track its usage or modification would be ineffective due to the dynamic nature of the properties. This also applies to IDEs that offer a "Find all usages" feature for a specific property. By utilizing a distinct object, it becomes simpler for other developers to locate where the .day object is altered or accessed.

You can then implement the following (note that the use of [] eliminates the need for a .):

this.day[dayUpperCase].push(tmpTable);

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

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

Guide on Postman: Tracking the number of occurrences for a particular object in a JSON reply

I am just starting out with JSON and Postman. I have a simple task in mind. I have set up a GET request that will return a JSON response like the one below. In this example, I want to extract the count of all "IsArchived" attributes in the response. The ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

Issue with height in self-invoking function not functioning correctly

Issue with height not functioning correctly inside self-invoking function, but works fine within (document).ready(function() (function($){ var clientHeight = document.getElementById('home').clientHeight; alert(clientHeight); })(jQuery); <di ...

The issue of JQuery and document ready being triggered multiple times while loading data into a control

Ever since implementing the load function to load content into a DIV upon document ready, I've noticed that all associated functions are firing multiple times (often twice, and sometimes endlessly). The scripts included in the head tag of all pages a ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...

What is the reason that the for loop updates all indexes in Node.js?

Currently, I am working on a space battle program that involves nested arrays. In order to simulate fleet fighting, I have written the following code: //Roll a dice function const randomNumber = (number) => { return Math.floor(Math.random() * numbe ...

Error: Unable to access the toISOString property of an undefined object

https://i.sstatic.net/jtZnQ.png import './ExpenseItem.css'; function ExpenseItem(props){ return ( <div className="expense-item"> <div>{props.date.toISOString()}</div> <div className="expen ...

Steps for successfully sending data to a MenuItem event handlerExplanation on how to

My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render. The scenario involves having a ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

Error: Vue js - module store has not been defined

While working on my Vue.js project, I encountered an error message stating * ./store in ./src/main.js. Despite using the store in app.vue and verifying that it's functioning correctly with this.$store.dispatch("user", response.data.response);, I kept ...

Is it possible to include array elements in a dropdown menu using React?

Imagine you have an array called const places = [" a1", "a2", "a3"]; and <FormControl variant="outlined" className={classes.formControl}> <InputLabel id="dropdown_label">Testing</InputL ...

Using `popWin()` in conjunction with `echo php` in Javascript

How can I create a JavaScript popup window inside an echo line? I have tried the following code but the popup window does not work: echo '<td> <a href="javascript:popWin(edit.php?id='.$row[id].')">Edit</a></td>&apos ...

Understanding how to parse a JSON object in JavaScript is a

In my JSON object, I have the following data: rows = [{name:"testname1" , age:"25"}, {name:"testname2" , age:"26"}] My goal is to extract the names and store them in a variable like this: name = "testname1, testname2"; ...

Retrieve the JavaScript object that was initialized within a function

As I venture into the world of working with javascript objects and php objects, I've encountered an issue. While everything seems to be functioning correctly so far, I'm having trouble accessing the javascript object created in the ajax success r ...

What causes a never-ending loading cycle on a website when a 404 error occurs?

My Express.js/Node.js website is hosted on Heroku. I am facing an issue where the server does not properly send a 404 error when a file cannot be found. Instead, the page keeps loading endlessly. How can I make the server stop loading when it encounters a ...

Ways to showcase data from Spotify playlists

I'm in the process of accessing and displaying a user's Spotify playlist data in the app I'm developing. These are the steps I've followed so far, but I need assistance in identifying any errors: 1) Implement a method in Spotify.js ...

Efficient Data Extraction with PySpark from Multiple JSON Files

After uploading numerous JSONL files into Spark 2.2.0 from a directory using the command (python spark): df = spark.read.json(mydirectory) df.createGlobalTempView("MyDatabase") sqlDF = spark.sql("SELECT count(*) FROM MyDatabase") sqlDF.show(), I noticed th ...

Tips for successfully setting up a Python script to extract data from .txt files and calculate the total number of positive values

I am dealing with a Python script that is supposed to analyze a directory containing .txt files and determine whether each file returns positive or negative for specific text statements like "known infection source" within the file itself. Unfortunately, m ...

Passing props to another component using the <Link> element in React Router

I'm working on a project where I need to display search results using an array. When a user clicks on an item, I want to pass that item as props rather than as parameters. Below is the code snippet: { this.props.results.map((result) => { ...