Transform a string into a variable

When receiving JSON data from AJAX, I often find myself working with multiple variables. For example, I may have data stored in variables like data.output_data_1234 and data.output_data_5678.

To work with these variables more effectively, I convert them to arrays. This can be achieved with the following code:

var outputdataarr = new Array(data.output_data_1234);

While this method works well, I sometimes encounter the need to add a number to the variable name. I attempted the following code, but unfortunately, it did not yield the desired result:

var outputdataarr = new Array('data.output_data_'+formid+'');

It's important to note that formid contains a valid number.

Another approach I tried was accessing the variable using window[] syntax, as shown below. However, this method also did not provide the expected outcome:

var outputvar = window['data.output_data_' + formid];
var outputdataarr = new Array(outputvar);

If you have any insights or suggestions on how to tackle this issue, I would greatly appreciate your help. Thank you in advance!

Answer №1

It looks like you're looking for something along these lines:

var outputdataarr = new Array(data['output_data_'+formid]);

Remember, when using square brackets as an object field identifier, you can only use strings and not periods.

UPDATE: To populate the entire array, you may need to use a loop like this:

var outputdataarr = new Array();    
for (var i=1000; i<2000; i++) {
  outputdataarr.push(data['output_data_'+formid]);
}

Answer №2

It is advisable to utilize square brackets [] in place of new Array for improved performance.

var outputDataArray = [];
outputDataArray.push(data['output_data_' + formId]);
// continue with other operations

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

The Bootstrap modal simply fades away without ever making an appearance

My bootstrap modal is not displaying on desktop, only showing a faded screen. It works fine on mobile and tablet devices. Any ideas why this might be happening? Here is the code: <button type="button" class="btn btn-primary" data-to ...

Unable to display text overlay on image in AngularJS

I am experiencing an issue with displaying captions on image modals. .controller('HomeController',['dataProvider','$scope','$location', '$modal', '$log', 'authService', function ...

The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always ...

The issue of "400 Bad Request Error" in Wordpress's admin-ajax.php file is

I am attempting to send data from a form using AJAX. Initially, I have a button labeled "add file". When this button is clicked, the form is displayed via AJAX and it functions correctly. However, upon submitting the form, I encounter a bad request error ...

I'm wondering if it's possible to fork an npm library in package.json and automatically trigger its build process upon installation

I am currently facing an issue with a npm dependency, such as ngx-infinite-scroll, that I am trying to fork for bug fixes. I want to include my modified version as a dependency in my application. Here is an example of how I have included it in my package.j ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

I am encountering a challenge retrieving the ID via AJAX from the view to the controller. However, the ID is successfully displaying in the alert

In the view page code below, I am trying to send an ID through Ajax but it is not posting in the controller. The goal is to replace one question at a time fetching from the database. $(document).ready(function() { $("#next").click(function() { ...

Preserving the initial input values in a secure manner for future reference, utilizing either an object or a

Recently, I've started revisiting a script I created a while back that checks for changes in a form to prompt a message asking 'Would you like to save your changes?'... One thing that's been on my mind is whether I should store the ori ...

Display a textarea field on the current page using AJAX technology

My goal is to display the value of a textarea input in real-time by utilizing the keyup event in my showContent div. However, I lack expertise in Ajax and/or JQuery and would appreciate some assistance. The form located in formPage.phtml (I'm unsure ...

Displaying a loading animation to keep users engaged while AJAX calls retrieve data from the server

My issue was outlined in a recent discussion on Stack Overflow. In essence, my goal is to display a loading indicator before server-side processes complete: [Loader] -> [Target page]. However, the HTML content loads after the server-side tasks, resultin ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

React is having difficulty locating a specific module

I've been attempting to install the parallax library from https://github.com/wagerfield/parallax/. I have gone through the documentation and even found a sample usage in JavaScript. Planning to integrate it into React, based on the sample code and Rea ...

Is it possible to simultaneously play several one-shot sound effects on mobile web browsers?

I'm attempting to trigger a sound effect when the user clicks a button on my web application. Initially, I experimented with this approach: var sound = new Audio("soundeffect.ogg"); function clickHandler(){ sound.play(); } Unfortunately, if the ...

Retrieve 10000 sets of coordinates in real time with the help of Google Maps

I am trying to retrieve coordinates for 10,000 lines of data using the Google Maps geocoding API and display each line on the browser. My strategy involves looping through each line (which contains an address), passing it to the Google Maps URL, parsi ...

Initiate a POST request using cURL to interact with an AJAX

Struggling with implementing the Zendesk API curl https://{subdomain}.zendesk.com/api/v2/tickets.json \ -d '{"ticket":{"subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \ -H "Content-Type: ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

Is there a method in Express to verify which URL a post is being sent to?

At the moment, I am using express to proxy my session creation URL in the following manner: app.post('/sessions', (req, res) => { // Code goes here }) The code that is used for this proxy also needs to be applied to my /confirmation endpoi ...

What is the reason for both the d3 line chart and bar chart being shown simultaneously?

On my website, I have implemented both a d3 bar chart and a line chart. You can view examples of them here: line_chart and bar_chart. However, in certain situations only one of the charts is displaying instead of both. Can anyone provide guidance on how ...

Tips on executing array manipulations

After running a select query using Yii's cdbcommand, I obtained an array structured as follows: Array( [0] => Array( [0] => Array ( [id] => 21 ) [1] => Array ...

"Encountering a problem with Django URLs while attempting to access an AJAX function

In my urls.py file, I have defined a URL pattern as follows: url(r'^level/(\d+)/ajax/reload/$', views.ajax_change_status, name='ajax_change_status'), # This URL also works fine url(r'^level/ajax/reload/$', views.ajax_c ...