Call to dynamic Javascript variable

1

How about. My question is this:

I create a variable in javascript within an each:

window["opcion" + v.id] = {var1: 1, var2: 2};

If I want to access it within it each, how should I refer to it?

It could be like this: "opcion"+v.id ó opcion+v.id

I hope you can answer my question.

    
asked by Pedro Emmanuel Llergo Gonzalez 15.12.2017 в 15:37
source

2 answers

3

Using the first option you can achieve it:

var v = {id:1}
window["opcion" + v.id] = {var1: 1, var2: 2};

// accedemos al objeto utilizando acceso por indice
console.log(window["opcion"+v.id]);
console.log(window["opcion"+v.id].var1);
console.log(window["opcion"+v.id].var2);

Javascript is a very dynamic language so it helps us a lot in certain circumstances.

    
answered by 15.12.2017 в 15:40
1

We do each to a select to get each of its children option that for each iteration we add a new value to the global variable window I hope it's what you're looking for

If you want to add to use the values later you can use the function push and add values for each iteration.

I hope you help greetings.

$("#myselect").find("option").each(function(){
  window["option"+$(this).attr("value")] = {var1: 1, var2: 2};
  //obtener el objeto completo
  console.log("objeto:",window["option"+$(this).attr("value")])
  //obtener la propiedad var1 dentro del objeto
  console.log("var1:",window["option"+$(this).attr("value")].var1)
  //obtener la propiedad var2 dentro del objeto
  console.log("var2:",window["option"+$(this).attr("value")].var2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect" class="" name="">
    <option value="opcion1">opcion 1</option>
    <option value="opcion2">opcion 2</option>
    <option value="opcion3">opcion 3</option>
    <option value="opcion4">opcion 4</option>
  </select>
    
answered by 15.12.2017 в 16:34