Sanan Ali
Sanan Ali

Reputation: 3444

How to Convert String to Variable Name in Vue JS

hope you are all doing great. I want to know is there any way we can convert string to a variable name? I want to convert "minXLabel" to minXLabel and use it inside span tags like this <span>{{minXLabel}</span> I 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 is

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

I can do that manually with <span>{{ minXLabel || placeholder[index].first}} - </span> but because I want to output in a loop with different keys I need to convert that string into a variable name.

Upvotes: 1

Views: 1316

Answers (1)

Jorge Cordero
Jorge Cordero

Reputation: 190

You can transform a string to variable using eval function, something like this

 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)
  }

However, these variables will not be declared, you can assign value if you want for example inputsArray[index].firstOption || placeholder[index].first and then use the variable.

However, looks a little redundant that you try to assign a value that you already have to a new variable. For me, your first approach is correct just loop over your array and render the info there

<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> 

Upvotes: 1

Related Questions