Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this:

<span>{{minXLabel}</span>
. I currently have

        <div class="placeholder-value">
         <span>{{  inputsArray[index].firstOption || placeholder[index].first}} - </span> 
         <span>{{  inputsArray[index].secondOption || placeholder[index].second}}</span> 
       </div>

and the input array looks like this:

 inputsArray : [
        { 'firstOption': "minXLabel", 'secondOption': "maxXLabel" },
        { 'firstOption': "minXLabel", 'secondOption': "minYLabel" },
        { 'firstOption': "maxYLabel", 'secondOption': "maxXLabel" },
        { 'firstOption': "maxYLabel", 'secondOption': "minYLabel" }
      ],

I could do it manually with

<span>{{  minXLabel || placeholder[index].first}} - </span>
, but since I want to iterate over different keys in a loop, I need to find a way to dynamically convert strings into variable names.

Answer №1

To convert a string into a variable, you can utilize the eval function in the following manner:

 const inputsArray = [
    { 'firstOption': "minXLabel", 'secondOption': "maxXLabel" },
    { 'firstOption': "minXLabel", 'secondOption': "minYLabel" },
    { 'firstOption': "maxYLabel", 'secondOption': "maxXLabel" },
    { 'firstOption': "maxYLabel", 'secondOption': "minYLabel" }
  ]

  const iterator = inputsArray.values()

  for (let item of iterator) {
    const variableName = eval(item.firstOption);
    console.log(variableName)
  }

Keep in mind that these variables will not be declared initially. If needed, you can assign values by accessing them with code like

inputsArray[index].firstOption || placeholder[index].first
, and then use those variables.

However, it seems somewhat redundant to assign a value you already possess to a new variable. In my opinion, your original approach is most suitable—simply loop over the array and render the information accordingly:

<div v-for="item in placeholder">
  <div v-for="input in inputsArray" class="placeholder-value">
     <span>{{  input.firstOption || item.first}} - </span> 
     <span>{{  input.secondOption || item.second}}</span> 
  </div>
</div> 

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

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

What is the syntax for populating an attribute on the same line as v-for in Vue.js?

I am currently working on a simple loop utilizing Vue to iterate over an array of objects and populate table rows. <tr v-for="user in users"> <td>{user.name}</td> <td>{user.id}</td> </tr> However, I also need to as ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

Import the complete JSON file into a variable as an array

I am struggling with loading an external json file (locations.json) into a variable and then using the information found here: http://www.json.org/js.html Despite trying various methods, I have not been successful in populating the variable. Even after fo ...

Attempting to create a school project involving pizza, but encountering some technical difficulties

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>pizza ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

Using ReactJS to strip HTML tags from JSON response

I'm having trouble figuring out how to strip HTML tags from a JSON response in reactjs. Here's the JSON response: { "price": "26,800.98", "diff": "<!--daily_changing-->+13.44 (+0.05%)&nbsp;& ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

Is there a way to remove specific elements from an array without using jQuery?

I've recently started diving into Javascript, experimenting with Tampermonkey scripts for the past week. The webpage I'm currently working on features dynamic elements that appear randomly with each page load. Sometimes only one element like "he ...

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

Using JavaScript to add a JSON string from a POST request to an already existing JSON file

I am currently working on a basic express application that receives a post request containing JSON data. My goal is to take this data and add it to an existing JSON file, if one already exists. The key value pairs in the incoming JSON may differ from those ...

jQuery - class remains unchanged on second click event

Operations: Upon clicking on an element with the class thumb_like or thumb_unlike, a like will be added or removed for the image using a POST request. The element with the class thumb_count will increase or decrease based on user actions. For example, lik ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

What is the best way to programmatically route or navigate to a specific route within a Next.js class component?

tag: In the process of creating my app with next.js, I primarily use functional components. The sole exception is a class component that I utilize to manage forms. Upon form submission, my goal is to redirect back to the home page. However, when I attemp ...

Vuetify chip displaying lengthy text

Is there a workaround for the issue of the text being cut in the Vuetify component v-chip when it is too long? new Vue({ el: '#app', vuetify: new Vuetify(), data() { return { } }, }) <link href="https://cdn.jsdel ...

Switch between various components using multiple buttons in Next.js

I am in the process of creating a component that will display different components depending on which button the user selects. Here are the available “pages”: ` const navigation = [ { name: "EOQ", return: "<EOQgraph />" }, { nam ...

Choose a random element from a string with Javascript

Could someone please help me figure out why my code isn't functioning as expected? I'm trying to randomly select three names from a list and ensure that no name is repeated. While I believe I am on the right track, something seems to be missing. ...

Cypress and VueJS: How to target elements that are dynamically generated following a specific user interaction

I am currently testing a new feature where a button will only appear for the user to click after they have completed another action. Before proceeding with the action, I am verifying if the button exists: cy.get('span') .contains('Selec ...

Downloading a folder in Node.js using HTTP

Currently facing an issue with downloading a folder in node js. The problem arises when I make an HTTP request for a whole folder and receive a stream that contains both the folder and files. Existing solutions (like fs.createWriteStream) only seem to work ...

Transferring Information from Angular Interface to NodeJS through a JSON Document

I am currently working on establishing a connection between an AngularJS front end and a NodeJS back end application. The main objective is to manipulate data in a JSON file instead of a traditional database. I have attempted to set up the post method on ...