Question about inserting a Javascript Object

6

Context

I'm trying to persist in the database of a purchase, as well as all of its items. For this I am using a .jsp file. But I need to send the web page data. Purchasing data is easy. The problem is in the items of the same, I wanted to do something dynamic, letting the user insert as many items as needed. But I came across a logic error that I'm not sure how to solve: In the OnChange event of the barcode input, I perform an Ajax request that goes to the Database, selects the product that owns that Barcode, and returns the its entire object. When doing this, I need to insert the same into an array of Javascript objects, however, at that point comes my problem.

Problem

I can not define a dynamic object, when I update the attributes of the object coming with the Ajax data, and I insert in the Array, if the user wants a new object (Product), it overwrites the same object, so I have several objects within the Array, with the same values. If you can or will try to help me, I will be extremely grateful.

JS code

$("#cbarras").on('change', function() {

       var cbarras = $('#cbarras').val();
       var cliente =  $('#cliente').val(); 
       var data = $('#data_compra').val();
       var quantidade = $('#quantidade').val();

       if (cbarras && cliente && data && quantidade){
           $.ajax({
             url : "http://localhost:8080/ProjBiltiful/BuscarProduto.jsp?id=" + cbarras,
             dataType : "json",
             success : function(data){
             if (data){
                 var total_item = data.vvenda * quantidade;
                 total += total_item;
                 $('#total_venda').val(total);

                 //INCLUO OS ITENS DA VENDA EM UM ARRAY DE OBJETOS
                 obj_itens.cbarras = data.cbarras;
                 obj_itens.valor = data.vvenda;
                 obj_itens.qtd = quantidade;
                 obj_itens.total = total_item;


                 itens_venda.push(obj_itens);

                 obj_itens.cbarras = 0;
                 obj_itens.valor = data.vvenda;
                 obj_itens.qtd = 0;
                 obj_itens.total = 0;

                 console.log(itens_venda);

                 $('#table_itens tbody').append(
                   '<tr class="child">'
                      + '<td align="center">' + data.cbarras + '</td>'
                      + '<td align="center">' + data.nome + '</td>'
                      + '<td align="center">' + data.vvenda + '</td>'
                      + '<td align="center">' + quantidade + '</td>'
                      + '<td align="center">' + total_item + '</td>' +
                    '</tr>'
                 );

                  } else {
                    alert('Produto não encontrado !');
                  }
              },
                error: function(err){
                  alert('Ooops... Encontramos um erro ao buscar o produto');
                }
            });
        } else {
          alert("Você deve ter esquecido de preencher algum campo da venda!");
        }
});
    
asked by anonymous 05.02.2017 / 07:09

1 answer

4

In your code, you did not show where you are setting obj_itens , but you realize that it is not declared within the scope of the anonymous function passed as callback to the success .

Objects are always treated as " reference " in JavaScript. This means that at each invocation of this function, you are overwriting the same object.

In fact, unlike what you said, you do not have multiple objects in the Array, but you're adding the same object again, and each time you update the value of it, applies to all Array items (because it is the same object / same reference).

To solve this, you must create a new object within your function and add this new object to the Array. Something like this:

$.ajax({
   /* ... */
   success : function(data){

    /* ... */

    var novo_item = {}; //novo objeto

    novo_item.cbarras = data.cbarras;
    novo_item.valor = data.vvenda;
    novo_item.qtd = quantidade;
    novo_item.total = total_item;


    itens_venda.push(novo_item);

    console.log(itens_venda);

    /* ... */


  } /*, ... */
});

I hope I have helped.

    
05.02.2017 / 07:48