Generating variables programmatically from an array within the Ajax success callback

Hi there, I am currently working with an AJAX call and have the following code:

$.each(data.my_json, function(i, item) {

    const op_id = item.op_id;
    const op_name = item.op_name;

    let  nv_tmp_totals = item.nv_tmp_totals;
    let nvc_tmp_totals = item.nvc_tmp_totals;
    let  iniz_totals = item.iniz_totals;
    let deft_totals = item.deft_totals;
    let rmkt_totals = item.rmkt_totals;

    let nv_tmp_average = item.nv_tmp_average;
    let nvc_tmp_average = item.nvc_tmp_average;
    let iniz_average = item.iniz_tmp_average;
    let deft_average = item.deft_tmp_average;
    let rmkt_average = item.rmkt_tmp_average;

})

I want to optimize my code by using a loop for assigning variables. Currently, the code is repetitive and not efficient.

const source = ['rmkt', 'iniz', 'deft','nvc_tmp','nv_tmp'];

$.each(data.my_json, function(i, item) {

    const op_id = item.op_id;
    const op_name = item.op_name;

    for (let i=0; i<source.length; i++) {
                                    
        window[source[i]+"_totals"] = parseFloat(item.source[i]+"_totals")
                            
        window[source[i]+"_average"] = parseFloat(item.source[i]+"_average")
                                    
    }

})

Answer №1

Do you mean something similar to this example?

for key, value in data.items():
    globals()[key] = value

The global namespace will now have all the variables from the dictionary.

Python documentation on globals()

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

Collaborate on global functions across the Quasar ecosystem and beyond, including Vue3

Is it plausible to utilize this method for sharing functionality (not data, which is handled by stores) in a Quasar and Vue3 application? // boot/generic_stuff.js import {boot} from 'quasar/wrappers' const function_list = { /* content goes here ...

Connecting AngularFirebaseAuth: Running server API immediately following Firebase authentication?

My authentication process relies on two key factors: Using Firebase auth (email and password) Making a server API call to retrieve the complete customer entity from the database based on the firebaseID. The user must exist in both places for successful a ...

Looping through iterations to create circular patterns

How can I fix my code to draw multiple circles in a loop instead of just one? var ss_links_canvas = document.getElementById("ss_links_canvas"); ss_links_canvas.width = images.length * 41; ss_links_canvas.height = 25; var ss_links = ss_links_canvas.getCont ...

The Ajax request retrieves the whole webpage instead of only the expected echo result

When I make an ajax call to a .php page to query the database for a numerical value, the entire HTML file is returned instead of just the number I need. Here is my ajax script: <script type="text/javascript"> $(document).ready(function() { $("# ...

Simultaneously sending requests with REST API and Ajax

Is it considered problematic to send multiple ajax requests simultaneously to various endpoints of a REST API that ultimately end up affecting the same resource? Please note: each endpoint will be responsible for modifying different properties. For insta ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Embed a JavaScript file containing PHP code

Recently, I incorporated PHP into my JavaScript code, as shown below: var currentTotalContribution = <?php echo $myContribution; ?>; Now, I am interested in moving that content to my JavaScript file and importing it. I am unsure if this is achievab ...

The useStarRating() hook continues to display 0 even after the user has interacted with the star component

I've created a custom useStarRating hook to manage the state of a star rating component in my React project. Everything seems to be working properly, but I'm facing an issue with retrieving the updated value of currentValue after the user interac ...

Mastering Protractor's end-to-end control flow and managing time outs

When testing an angular app using protractor, I encountered a strange issue recently. Every now and then, or since a recent update, protractor seems to stall or slow down significantly. After investigating the problem, I discovered that a simple someEleme ...

Mastering the Art of Merging 3 Arrays

Greetings to the Community I have a question regarding my code. I am looking to merge three variables together. $result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS `totalM`, SUM(CASE WHEN gender ...

Is it possible to alter the canvas origin when using an Orthographic camera with a CSS3D

When transitioning the camera from perspective to orthographic, I noticed that the camera's position also shifts so that the coordinates 0,0,0 are situated in the top left corner. Is this expected behavior? Check out this Example for reference. Ortho ...

showing the upload preview and disabling automatic uploading in Dropzone with React

Currently, when the user clicks the upload button and selects a file, it automatically uploads the file. However, I do not want this automatic upload to happen. Instead, I want to display the selected files to the user first before uploading them. I need ...

Display a portion of the existing URL as a clickable link on the webpage using JavaScript or PHP

If I have a website with the URL and I would like to showcase the image at https://example.com/image.jpg on my site (), what can I do? I attempted the following approach, but it only displays the URL of the image. <p id="image"></p> <scri ...

What is the best way to apply a Javascript function to multiple tags that share a common id?

I am experimenting with javascript to create a mouseover effect that changes the text color of specific tags in an HTML document. Here is an example: function adjustColor() { var anchorTags = document.querySelectorAll("#a1"); anchorTags.forEach(func ...

Navigating arrays comprised of other arrays

I have recently updated the structure of my array and encountered a misunderstanding on my part. The array now appears as follows: array:9 [▼ 0 => array:4 [▼ "leadData" => array:7 [▼ "LeadID" => "1232806" "Client" => "S ...

Troubles with AJAX comment system validation issues

Having created a webpage that displays articles with a textarea under each article for user comments, I implemented AJAX successfully. The validation also works fine - if the textarea is empty, it will display an error and not submit the comment. However, ...

Encountered an issue when accessing a C# Webservice via AJAX - returning a Dataset as the output

This is my initial exposure to C# Web Service & AJAX. I am interested in creating a page similar to Facebook, where the next set of records loads as we scroll down. Although I have attempted to implement the code, it is not functioning as expected. Can an ...

issues arising from a growing css division

I am facing an issue where the tiles on my webpage expand on hover, but some of them are partially covered by neighboring tiles. How can I resolve this problem? Here is the CSS code snippet: .tile { position: absolute; width: 86px; background-color ...

Creating an interactive webpage with Javascript and HTML

I'm facing a challenge with my component setup, which is structured as follows: import { Component, VERSION } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ ...

PHP script for executing commands in a sequential order

Can anyone help me with writing a script that will run commands sequentially, one after the other, waiting for each to finish before starting the next? php bin/console SOME:CUSTOM:COMMAND <PART_1_ARGUMENT> <PART_2_ARGUMENT> --env=xxx I have ...