Create an array with objects in Javascript

Asked

Viewed 28,540 times

4

I have defined the object, and the array in the scope.

//Define o array que deve ser preenchido com os objetos
var itensList = [];

//Define os argumentos do objeto
var oItem = {
    Codig: 0,
    Desc: "",
    Unid: "KG",
    Quant: 0,
    Custo: 0,
    IL: "",
    Centro: "",
    Saldo: o
}

So for each row of the DHTMLX Grid, include the results in the object...

        //Para cada linha do grid, busca os resultados
        mygrid.forEachRow(function (id) {
            //Se o Codigo do item for maior que zero..
            if (mygrid.cells(id, 0).getValue() != 0) {
                // .. adiciona os valores ao objeto
                oItem.Codig = mygrid.cells(id, 0).getValue();
                oItem.Desc = mygrid.cells(id, 1).getValue();
                oItem.Unid = mygrid.cells(id, 2).getValue();
                oItem.Quant = mygrid.cells(id, 3).getValue();
                oItem.Custo = mygrid.cells(id, 4).getValue();
                oItem.IL = mygrid.cells(id, 5).getValue();
                oItem.Centro = mygrid.cells(id, 6).getValue();
                oItem.Saldo = mygrid.cells(id, 7).getValue();
                // Adiciona o objeto a lista
                itensList.push(oItem);
            }
        });

At the end of this program, if I have two lines filled in the Grid, it will have an array, with two objects, each with the parameters listed above, but, the two stay with the same values, the values of the last line swept by the code, ie two objects equal, when the lines are different. Debugging, I saw that when adding the object to the array with itensList.push(oItem);, it makes the object that is already there have the same values.

How to make each object have the values of each line?

3 answers

3

This happens pq vc is inserting the same object into the vector. By changing the field value, it changes the references in the vector.

One way to settle this would be clone the object.

Another way, simpler, would be to change the variable declaration to within the if.

mygrid.forEachRow(function (id) {
  //Se o Codigo do item for maior que zero..
  if (mygrid.cells(id, 0).getValue() != 0) {
    var oItem = {};

    // .. adiciona os valores ao objeto
    oItem.Codig = mygrid.cells(id, 0).getValue();
    oItem.Desc = mygrid.cells(id, 1).getValue();
    oItem.Unid = mygrid.cells(id, 2).getValue();
    oItem.Quant = mygrid.cells(id, 3).getValue();
    oItem.Custo = mygrid.cells(id, 4).getValue();
    oItem.IL = mygrid.cells(id, 5).getValue();
    oItem.Centro = mygrid.cells(id, 6).getValue();
    oItem.Saldo = mygrid.cells(id, 7).getValue();

    // Adiciona o objeto a lista
    itensList.push(oItem);
  }
});
  • 1

    One remark: in fact the var can stay out of the if, at the top of the function. There is no "scope of if" in js.

  • 1

    @bfavaretto Indeed. I meant "inside" the if.

2

The problem is that you are setting the same "instance" of the item object, and it will be modified in all its references, since it is being declared in a global scope in javascript.

In Javascript you don’t need to declare the structure of your object, since the javascript objects are dynamic, you can do just that:

//Para cada linha do grid, busca os resultados
mygrid.forEachRow(function(id) {
    //Se o Codigo do item for maior que zero..
    if (mygrid.cells(id, 0).getValue() != 0) {
        // .. adiciona os valores ao objeto
        var oItem = new Object(); // cria um objeto novo (uma nova instância)
        oItem.Codig = mygrid.cells(id, 0).getValue();
        oItem.Desc = mygrid.cells(id, 1).getValue();
        oItem.Unid = mygrid.cells(id, 2).getValue();
        oItem.Quant = mygrid.cells(id, 3).getValue();
        oItem.Custo = mygrid.cells(id, 4).getValue();
        oItem.IL = mygrid.cells(id, 5).getValue();
        oItem.Centro = mygrid.cells(id, 6).getValue();
        oItem.Saldo = mygrid.cells(id, 7).getValue();
        // Adiciona o objeto a lista
        itensList.push(oItem);
    }
});

And remove the object declaration:

//Define os argumentos do objeto
var oItem = {
    Codig: 0,
    Desc: "",
    Unid: "KG",
    Quant: 0,
    Custo: 0,
    IL: "",
    Centro: "",
    Saldo: o
}

2

You need to clear the variable oItem, keep her creation out of the loop and try this:

 //Para cada linha do grid, busca os resultados
        mygrid.forEachRow(function (id) {
            //Se o Codigo do item for maior que zero..
            if (mygrid.cells(id, 0).getValue() != 0) {
                // .. adiciona os valores ao objeto

                oItem = {}; // AQUI eu inicializo a variável

                oItem.Codig = mygrid.cells(id, 0).getValue();
                oItem.Desc = mygrid.cells(id, 1).getValue();
                oItem.Unid = mygrid.cells(id, 2).getValue();
                oItem.Quant = mygrid.cells(id, 3).getValue();
                oItem.Custo = mygrid.cells(id, 4).getValue();
                oItem.IL = mygrid.cells(id, 5).getValue();
                oItem.Centro = mygrid.cells(id, 6).getValue();
                oItem.Saldo = mygrid.cells(id, 7).getValue();
                // Adiciona o objeto a lista
                itensList.push(oItem);
            }
        });

Or not to lose the properties initially set:

 //Para cada linha do grid, busca os resultados
        mygrid.forEachRow(function (id) {
            //Se o Codigo do item for maior que zero..
            if (mygrid.cells(id, 0).getValue() != 0) {
                // .. adiciona os valores ao objeto

                var oItem = { // AQUI eu inicializo a variável
                  Codig: 0,
                  Desc: "",
                  Unid: "KG",
                  Quant: 0,
                  Custo: 0,
                  IL: "",
                  Centro: "",
                  Saldo: o
                } 

                oItem.Codig = mygrid.cells(id, 0).getValue();
                oItem.Desc = mygrid.cells(id, 1).getValue();
                oItem.Unid = mygrid.cells(id, 2).getValue();
                oItem.Quant = mygrid.cells(id, 3).getValue();
                oItem.Custo = mygrid.cells(id, 4).getValue();
                oItem.IL = mygrid.cells(id, 5).getValue();
                oItem.Centro = mygrid.cells(id, 6).getValue();
                oItem.Saldo = mygrid.cells(id, 7).getValue();
                // Adiciona o objeto a lista
                itensList.push(oItem);
            }
        });
  • 1

    Remembering that the first option considers that the variable is already declared out (otherwise, it creates an implicit global, bad practice).

  • 1

    @bfavaretto Exact! I even complemented my answer :) Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.