Two arrays in foreach js

0

I have a function in JavaScript that sends requests with the contents of the lines of a textarea , is a looping that runs through an array and sends the requests with the data of these indexes of the array, the problem is that I need to create 1 more array with the contents of another textarea and send simultaneously with the array of the first textarea , in case:

<script>
  function enviar(){
    var bin = $("#bin_id").val();
    var linhaenviar = bin.split("\n");
    var cor = coloracao.split("\n"); //esse e o textarea do qual quero criar o array
    var index = 0;
    linhaenviar.forEach(function(value){
      setTimeout(
        function(){
          $.ajax({
            url: 'bancodedados.php',
            type: 'POST',
            dataType: 'json',
            data: 'nome=' + value + 'cor=' +arraycor,
            success: resultado
        })
      }, 10 * index);
    index = index + 0;
    })
  }
</script>
    
asked by anonymous 23.01.2018 / 04:41

1 answer

2

I believe this is what you want. In front of 2 arrays, make a forEach on the largest and pull each index simultaneously from the smallest to the limit:

function enviar(){
    var bin = $("#bin_id").val();
    var coloracao = $("#coloracao").val();
    var linhaenviar = bin.split("\n");
    var cor = coloracao.split("\n"); //esse e o textarea do qual quero criar o array
    var index = 0;
    
    var comp = linhaenviar.length >= cor.length;
    var maior = comp ? linhaenviar : cor;

    maior.forEach(function(value, i){

      var arraycor = comp ? (cor[i] != null ? cor[i] : ''): value;
      var linha = !comp ? (linhaenviar[i] != null ? linhaenviar[i] : ''): value;

      setTimeout(
         function(){
           console.log(linha+" / "+arraycor);
//            $.ajax({
//               url: 'bancodedados.php',
//               type: 'POST',
//               dataType: 'json',
//               data: 'nome=' + linha + 'cor=' +arraycor,
//               success: resultado
//        })
      }, 10 * index);
    index = index + 0;
    })
  }
textarea{
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="bin_id">linha1
linha2
linha3
linha4
linha5
linha6</textarea>

<textarea id="coloracao">cor1
cor2
cor3
cor4
cor5</textarea>

<br />
<button onclick="enviar()">Enviar</button>
    
23.01.2018 / 06:07