Doubt about inserting Javascript object

Asked

Viewed 221 times

6

Context

I am trying to make the persistence in the database of a purchase as well as all of its items. For this I am using a file .jsp. But I need to send the data from a web page. The purchase data is easy. The problem is in the same items, I wanted to do something dynamic, letting the user enter as many items as necessary. But I came across a logic error that I am not able to solve: In the Onchange event of the barcode input, I perform an Ajax request that goes to the database, selects the product that has that barcode and returns the entire object. In doing so, I need to insert it into an array of Javascript objects, but at this point comes my problem.

Problem

I cannot define a dynamic object, when I update the attributes of the object coming with the data from Ajax, and 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 would be most 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!");
        }
});

1 answer

4


In your code, you haven’t shown where you’re setting obj_itens, but it is perceived that it is not declared within the scope of the past anonymous function as callback by key Success.

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

In fact, unlike what you said, you don’t have multiple objects in the Array, but you’re adding the same object again, and each time you update its value, this applies to all items in the Array (as it is the same object/same reference).

To solve this, you must create a new object within its function and add this new object into 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’ve helped.

  • mrlew, THANK YOU VERY MUCH! IT HELPED ME A LOT, that’s right, I knew I was with the same object, but I didn’t know how to change it! It really helped me a lot! I thought I would have to modify the whole architecture of my logic! How do I give you the highest score on this Forum? I’m new here too! Thanks, success!!!

  • +1 for the good answer. @Matheusminguini .

  • Okay, thanks, guys! You guys are awesome!

  • @Matheusminguini thanks rsrs that good it worked. Good luck on the project!

  • @Thank you Wilker! Hugs!

Browser other questions tagged

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