Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically name variables javascript

I need to dynamically create variables inside a loop, but i have no idea how. I have read about using eval(); but all i found it's just about dynamically changing the value inside the variable.

I need something like this:

$(e).find('unidadeid').each(function () {
    countUnidades++;
    var Unidade[value inside countUnidades here] = $(this).text();
});

Be clear about your steps, please. I ask not for a solution, but for a help, as a learning. Thank you ;)

like image 989
ghaschel Avatar asked Jan 17 '26 07:01

ghaschel


1 Answers

You have two options:

  1. Use an array:

    var unidades = [];
    $(e).find('unidadeid').each(function () {
        unidades.push($(this).text());
    });
    

    or

    var unidades = $(e).find('unidadeid').map(function () {
        return $(this).text();
    }).get();
    
  2. If you really, really want to have names that aren't just digits, use an object and bracketed notation:

    var unidades = {}, countUnidades = 0;
    $(e).find('unidadeid').each(function () {
        countUnidades++
        unidades['Unidade' + countUnidades] = $(this).text();
    });
    

    That creates an object, unidades, with properties like Unidade0, Unidade1, etc. Note that each receives an index, so you don't need countUnidades unless you want it for something else:

    var unidades = {};
    $(e).find('unidadeid').each(function (index) {
        unidades['Unidade' + index] = $(this).text();
    });
    
like image 60
T.J. Crowder Avatar answered Jan 20 '26 01:01

T.J. Crowder