skip to Main Content

I return my form as follows, in which I have two expected results for the 12th and two expected results for the 13th.

var data = [{
    Designacao: "Micro-ondas1",
    Capitulo: "Cozinha",
    Data: "2023-08-12",
  },
  {
    Designacao: "Exaustor cinzento 1",
    Capitulo: "",
    Data: "2023-08-12",
  },
  {
    Designacao: "Mesa - Castanha -8 Lugares",
    Capitulo: "Sala",
    Data: "2023-08-13"
  },
  {
    Designacao: "cama",
    Capitulo: "Quarto",
    Data: "2023-08-13",
  },
];

var linha = ``;

Object.keys(data).forEach(i => {

  Designacao = data[i].Designacao;
  Capitulo = data[i].Capitulo;
  Data = data[i].Data;

  if (Data != Data) {
    linha += `<div class="card-header">Data Passagem de Turno - ${Data}</div>`;
  }

  linha += `<div class="row col-md-12">
            <div class="col-md-4">
              <p class="form-label">Data </p>
              <input type="text" class="form-control" name="dataen" value="${Data}">
            </div>
            <div class="col-md-3">
              <p class="form-label">Código Utente </p>
              <input type="text" class="form-control" name="codigoen" value="${Capitulo}" disabled="disabled">
            </div>
            <div class="col-12">
              <p class="form-label">Diário de Enfermagem </p>
              <textarea rows="6" class="form-control" name="didiarenf" > ${Designacao} </textarea>
            </div>`;

  $(".histpturno").html(linha);

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="histpturno"></div>

I intend to separate the results by day. For example, before the first result of the 12th, show the header that is inside the if and then only show the header again when the results of the 13th are returned

I tried to achieve the expected with the if, but it doesn’t work, it never returns the header. The header I’m referring to is this one inside the if:

<div class="card-header">Data Passagem de Turno - ${Data}</div>

2

Answers


  1. if(Data != Data)

    Should be pretty obvious how that will never be true, no? Data is not going to change between the two read accesses on either side of the comparison operator here.

    You need to compare the current value, with that of the previous record you processed. Easiest, if you store the previous value into a variable, that you initialize with a value that won’t occur in the actual data (so that the check will return true on the first record already).

    var data = [{
        Designacao: "Micro-ondas1",
        Capitulo: "Cozinha",
        Data: "2023-08-12",
      },
      {
        Designacao: "Exaustor cinzento 1",
        Capitulo: "",
        Data: "2023-08-12",
      },
      {
        Designacao: "Mesa - Castanha -8 Lugares",
        Capitulo: "Sala",
        Data: "2023-08-13"
      },
      {
        Designacao: "cama",
        Capitulo: "Quarto",
        Data: "2023-08-13",
      },
    ];
    
    var linha = ``;
    var prevData = null; // initialize
    
    Object.keys(data).forEach(i => {
    
      Designacao = data[i].Designacao;
      Capitulo = data[i].Capitulo;
      Data = data[i].Data;
    
      if (Data !== prevData) { // compare; for safety using strict type checking
        linha += `<div class="card-header">Data Passagem de Turno - ${Data}</div>`;
      }
      prevData = Data; // update, so that this will hold the correct "previous" record on the next iteration
    
      linha += `<div class="row col-md-12">
                <div class="col-md-4">
                  <p class="form-label">Data </p>
                  <input type="text" class="form-control" name="dataen" value="${Data}">
                </div>
                <div class="col-md-3">
                  <p class="form-label">Código Utente </p>
                  <input type="text" class="form-control" name="codigoen" value="${Capitulo}" disabled="disabled">
                </div>
                <div class="col-12">
                  <p class="form-label">Diário de Enfermagem </p>
                  <textarea rows="6" class="form-control" name="didiarenf" > ${Designacao} </textarea>
                </div>`;
    
      $(".histpturno").html(linha);
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="histpturno"></div>
    Login or Signup to reply.
  2. From my above comment …

    "The OP might consider an approach which does not try to achieve everything at once, but would separate the data (re)structuring task from the (final) render task. Thus, the actually needed solution is in need of grouping and collecting data-items by any item’s same date, which e.g. could be achieved via reduceing the source data array into an object/index with same date-values as grouping keys. The reduced data-structure then is the base for the render process."

    function renderLogsFromDateIndex(rootNode, index) {
      rootNode.innerHTML = Object
        .entries(index)
        .reduce((dateItemMarkup, [date, logs]) => [
    
          dateItemMarkup,
          `<div class="card-header">Data Passagem de Turno - ${ date }</div>`,
    
          logs
            .reduce((logItemMarkup, { Data, Capitulo, Designacao }) =>
    
              `${ logItemMarkup }<div class="row col-md-12">
                <div class="col-md-4">
                  <p class="form-label">Data </p>
                  <input type="text" class="form-control" name="dataen" value="${ Data }">
                </div>
                <div class="col-md-3">
                  <p class="form-label">Código Utente </p>
                  <input type="text" class="form-control" name="codigoen" value="${ Capitulo }" disabled="disabled">
                </div>
                <div class="col-12">
                  <p class="form-label">Diário de Enfermagem </p>
                  <textarea rows="6" class="form-control" name="didiarenf" > ${ Designacao } </textarea>
                </div>
              </div>`, ''
            ),
    
        ].join(''), '');
    }
    
    const data = [
      { Designacao: "Micro-ondas1", Capitulo: "Cozinha", Data: "2023-08-12", },
      { Designacao: "Exaustor cinzento 1", Capitulo: "", Data: "2023-08-12", },
      { Designacao: "Mesa - Castanha -8 Lugares", Capitulo: "Sala", Data: "2023-08-13" },
      { Designacao: "cama", Capitulo: "Quarto",  Data: "2023-08-13", },
    ];
    
    const logsByDate = data
      .sort((a, b) => new Date(a.Data) - new Date(b.Data))
      .reduce((index, item) => {
        (index[item.Data] ??= []).push(item)
        return index;
      }, {});
    
    console.log({ logsByDate });
    
    renderLogsFromDateIndex(
      document.querySelector('.histpturno'), logsByDate
    );
    .card-header {
      margin: 20px 0 0 0;
      background: #eee;
    }
    .as-console-wrapper {
      left: auto!important;
      min-height: 100%;
      width: 60%;
    }
    <div class="histpturno"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search