In JavaScript, a variable's value can be assigned to another variable using the variable

I have a collection of predetermined variables. I dynamically assign a value to another variable, which ends up representing the name of one of the predefined variables. This allows me to easily determine which set variable to use on a particular section of the page.

var mwm = "blah"
var vp = "bleh"
var am = "bluh"

var mwm720 = "some link 1"
var mwm717 = "some link 2"
var vp720 = "some link 3"
var vp717 = "some link 4"
...

Subsequently, there are other scripts that run and assign a variable value based on certain conditions, corresponding to the names of those predefined variables.

var myClass = $(this).attr("class").split(' ')[1];
var currDiv = "div." + myClass;
var currVersion = $(this).parent().attr("id");
var linkVers = myClass + currVersion;

The value of the variable linkVers always turns out to be "mwm720", "mwm717", "vp720", etc. This mechanism helps determine when to utilize the mwmw720 or mwm717 (etc) variables.

Intended Outcome

I am seeking guidance on how to prompt/trigger the utilization of the actual value stored in the dynamic variable that corresponds to the variable name.

If alert(linkVers); produces "mwm720", how can I ensure that $(currDiv).html(linkVers); inserts the value associated with the mwm720 variable (which would be "some link 1"), rather than just the variable name itself?

If there is an alternative approach to achieving this objective, I am open to exploring different solutions.

Answer №1

To keep your variables organized, it's best to store them all within a single object. For example:

var data = {
    name: "John",
    age: 30,
    city: "New York",

    jobTitle: "Developer",
    salary: "$50,000",
    yearsExperience: 5
}

Then, you can easily access these variables within your function like this:

console.log(data[variableName]);

Answer №2

A more organized approach would be to avoid cluttering the window namespace with multiple variables and instead utilize an object.

var myLinks = {
    mwm720 : "some link 1",
    mwm717 : "some link 2",
    vp720 : "some link 3",
    vp717 : "some link 4"
};

Then, you can access a specific link like this:

var selectedLink = "mwm720";
console.log(myLinks[selectedLink]);

If you prefer the original method, you can use window with bracket notation.

var selectedLink = "mwm720";
console.log(window[selectedLink]);

Answer №3

If you want a solution, try using the function eval:

let myVar = "abc123";
let abc123 = "example link";

console.log(myVar); // will output abc123
console.log(eval(myVar)); // will output "example link"

In your specific scenario:

eval ( $(currentDiv).html(linkVersion) ); 

This should do the trick for you

Answer №4

A more dynamic approach would be to organize your variables based on version groups. This eliminates the need to concatenate the name with the version.

var content = {
    720: {
        wm: "some link 1",
        p: "some link 3",
    },
    717: {
        wm: "some link 2",
        p: "some link 4",
    }
};

You can easily access the correct version of the link text using:

var linkVersion = content[currVersion][myClass];

As the currVersion remains constant throughout the script's execution (since you are staying on the same page), you can optimize performance by caching the messages for the current version in the beginning. This eliminates the need to repeatedly search for the parent's id:

// Declare in a higher scope
var currentContent;

// Initialization (e.g. DOM ready)
// Some adjustments may be necessary depending on what $(this).parent() represents
var currVersion = $(this).parent().attr("id");
currentContent = content[currVersion];

// When retrieving the link text
var linkVersion = currentContent[myClass];

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

When the onClick event is triggered, my intention is to dynamically insert a new

I'm having trouble adding a new row on each click, as my code keeps replacing the existing row. I attempted moving the if statement outside the addTable function, but it didn't work as expected. I've tried multiple solutions without succes ...

What is the best way to create a clickable table from a nested array of objects?

I am currently working with an array of objects that holds some variable information and another array of objects containing more details. My goal is to create a table that initially displays the main array, and when a user clicks on a specific row, it sho ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Obtaining and storing multiple checkbox selections in a database using a JSP page

If users are required to input data on the first page, such as City, Country, and URL of the destination, and they need to select the type of destination from options like Winter, Christmas, and Summer (max 2 selections), how can these results be connected ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

Discover the steps for generating this graph using ZingChart

I have been experimenting with ZingChart in an attempt to replicate a chart that has the same look and functionality as this example: https://i.stack.imgur.com/PGNK3.png Despite making numerous adjustments to a bar chart, I have not been able to achieve ...

Transmitting an email form using AJAX, Bootstrap, and Jquery

I am attempting to email a form using the code snippet below. This is a modified version of Bootstrap Validator created by 1000hz. $('#form').validator().on('submit', function (e) { if (e.isDefaultPrevented()) { alert("not workin ...

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...

Preserving the video's aspect ratio by limiting the width and height to a maximum of 100%

I am trying to integrate a YouTube video using their embed code in a "pop-up". However, I am facing an issue where the video does not resize to fit within the height of its parent. I want it to be constrained by the div#pop-up that contains the video. Curr ...

JavaScript interval setting multiples

In my current situation, I have implemented a setInterval based code that continuously checks the value of an AJAX call response. Here is how it looks: var processInterval = setInterval(function () { var processResult = getVideoStatus(data.file_name) ...

What could be causing the absence of console.log output in my Netlify function logs?

I am facing an issue with my Netlify function that is scheduled to run every minute using the @netlify/functions package. The function makes API calls and logs the response, but I cannot see any output from the console.log statement in the Netlify function ...

Compiling with GatsbyJs throws an abrupt token error with 'if' being an unexpected token

I am working on a code snippet in GatsbyJS where I am extracting data from a StaticQuery using GraphQL and then rendering a component. The challenge I am facing is to conditionally check if a specific sub-object exists within the data object, and if it doe ...

Error handling in Mongoose callback functions

Currently, I am delving into nodejs, express and mongoose. A question has arisen in my mind regarding the findOne function used to fetch a document from the database. Typically, it is utilized like this: Product.findOne({_id: req.params.id},function(erro ...

What is the best way to eliminate the occurrence of the word 'undefined' from the cycle output?

Can anyone assist with solving this issue? The webpage on JSFIDDLE displays 4 news containers, but an 'undefined' string appears before the first news container. I am looking to remove that 'undefined' string. Here is the HTML code: ...

JavaScript Failing to Validate User Input in Form

I'm a beginner in JavaScript and I'm trying to validate a simple date of birth input, but for some reason, it seems that the JavaScript file is not working. No matter what I input, it always goes through, so I'm trying to figure out what&apo ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Enhancing ajax content with Rx.Observable.fromEvent: A step-by-step guide

I am currently fetching content using Ajax, in the form of a json object, which is then displayed in the browser. var stateSubjectSub = stateSubject.subscribe(function(data) { console.log('state changes'); console.log(data); var list = document ...

angular: setting default selected items in dynamically generated options

After looking at the example provided here, I noticed that all three select options have the same value. How can I ensure that each option has a different selected value? This is what I currently have: <li ng-repeat="tarea in tareas"> <inp ...

What is the best way to effectively link promise calls that rely on each other?

Here is the code snippet I am currently working with: const request = require('request-promise'); request(validateEmailOptions).then(function(result) { if (result.valid) { request(createUserOptions).then(function (response) { if (re ...