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

I am seeking a solution to this error that occurs whenever I attempt to call a function using a button

Issue " _ctx.hello is not a function TypeError: _ctx.hello is not a function at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/di ...

Encountering an error of undefined when trying to access the index parameter while looping through objects in vue

Take a look at the code snippet below. Here I am using v-for to iterate over the object. I am attempting to access the index parameter but it is coming up blank. <a href="#" class="list-group-item" v-for="(event, key, index) in events"> The ind ...

Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local ...

The Colorbox feature showcases images in their binary data format

I'm currently experimenting with using Colorbox to enhance a website that is being built with Backbone.js. Within my code, I have a straightforward image tag set up like this: <a class="gallery" href="/document/123"><img class="attachment-pr ...

The MIME type for .rar and .tar files is not specified

Why is it that Javascript (Windows 8.1, Firefox) doesn't seem to recognize mime types for .tar files or .rar files, among others? Is there a way to fix this issue without resorting to unconventional methods? I really need to be able to get the mime ty ...

What is the best way to display a webpage within an iOS app using PhoneGap?

In my iOS phonegap app, I am looking to have a single view that displays a web page. Can someone guide me on how to load this specific view with a particular URL using JavaScript? Although I primarily develop native iOS applications and do not have expert ...

What is the best way to manage uncaught errors within the simple-peer library?

Currently integrating feross' simple-peer library and encountering an occasional error: Uncaught Error: Ice connection failed. at r._onIceStateChange at RTCPeerConnection.t._pc.oniceconnectionstatechange This error is directly from the library and ...

Challenges with the Placement of Buttons

I am facing an issue with the code below: document.addEventListener("DOMContentLoaded", function(event) { // Select all the read more buttons and hidden contents const readMoreButtons = document.querySelectorAll(".read-more"); const hiddenConten ...

I am unable to view the Vuex state in components nested within v-tabs until the initial visit

Using the following dependencies: vuetify: ^2.5.10 vuex: ^3.6.2 vue: ^2.6.14 I have a project that utilizes v-tabs with a child component embedded in the first tab. Within this component, I have implemented a file input field and a button to ...

In nextjs, the page scroll feature stops functioning properly following a redirection

Currently, I am running on version 13.5.4 of Next.js In a server-side component, I am using the nextjs redirect function to navigate to another page. However, after the redirection, I noticed that the next page is missing the scroll bar and seems to be st ...

Having difficulty kicking off a fresh React project on Windows

I've encountered an issue while setting up my React application on Windows OS. After running npm start, the application fails to load on localhost:3000, showing the error message Cannot GET /. Below is the project structure: - webpack.config.js - p ...

Obtaining JSON data in an Angular service: A beginner's guide

My JSON file has the following structure: { "user": [ { "id": 0, "data": [ { "userName": "iheb", "useremail": "", "userPassword": "kkk" } ], "questionnaireListe": [ { ...

The code functions perfectly in the Adobe Dreamweaver Preview, but unfortunately, it is not compatible with Chrome

In the process of creating a website using Adobe Dreamweaver over the past few days, I encountered an issue with JavaScript that should activate upon scrolling. Interestingly, the script works perfectly fine when accessed through this link (), but fails t ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

Sending state information through props in a Vuex environment

One of the challenges I am facing is how to make a reusable component that can display data from the store. My idea is to pass the name of the store module and property name through props, as shown below: <thingy module="module1" section=" ...

Utilizing Props to Manage State within Child Components

Is it possible to assign the props received from a Parent Component as the state of a Component? export default class SomeComp extends Component { constructor(props) { super(props); this.state = someProps; // <-- I want to set the ...

Working with Variables in JavaScript and PHP Scripting Languages

I have a PHP script that displays all the folders (categories) on my website: echo "<ul>"; foreach(glob('category/*', GLOB_ONLYDIR) as $dir) { $dir = str_replace('category/', '', $dir); echo '& ...

Eliminate the hover effect from every element

Is there a method in CSS or Javascript that allows me to eliminate the hover effect on all elements? I am specifically looking for a solution that will disable the hover effect on mobile devices while keeping it intact on desktop. I attempted using pointer ...

The call to the hook is invalid. In order to use hooks, they must be called within the body of a function component in

So, in my upcoming application, I am incorporating the react-google-one-tap-login library which features the useGoogleOneTapLogin hooks that need to be invoked within a React component. However, when I attempt to use it in this manner: func() { useGoogle ...

Having difficulty with the javascript click() function in an html document

Thank you in advance for checking this out. In my web application, users can choose options from four separate drop-down menus. Once a selection is made, the software triggers a click() function that generates a new span element within a div: var activeF ...