jquery 将两列合并为一列,保留每列的值

j2cgzkjk  于 2023-02-12  发布在  jQuery
关注(0)|答案(3)|浏览(130)

我有一个表,其中包含一些数据,我想将其放入一个数组中。该表的布局可以随时更改,由用户决定每列的列标题(列标题成为数组中的关键字。在该表中,可以有多列具有相同的标题,但在这种情况下,数据位于一列或其他列中:

    • 全部唯一**

| 日期|说明|金额|
| - ------|- ------|- ------|
| 第一次|行|一百|
| 第二次|行|-50|

    • 标题重复**

| 日期|说明|金额|金额|
| - ------|- ------|- ------|- ------|
| 第一次|行|一百||
| 第二次|行||-50|
请注意,列的顺序由用户根据表的源进行定义(他上传到我的应用程序的csv)。到目前为止,我所拥有的代码可以很好地处理唯一的头文件,并且能够发现重复项的索引。对于重复项的情况,问题是在第一行,它将返回Amount:'',因为它将用后者覆盖前者。在第二行,它将返回预期的Amount: '-50'。我需要帮助来改进我的代码,使第一行在重复的情况下返回Amount: '100'
我的代码:

$('.importer').click(function(e){
        e.preventDefault();
        //quante colonne sono rimaste
        var cols= $(".tbi").find("tr:first th").length-1;
        //mappatura di ogni colonna
        var intestColonne = [];
        $('.tbi').find('tr:first th > select').each(function(){
            intestColonne.push($(this).val());
        });
        
        const importi=intestColonne.map((x, i) => x === 'importo' ? i : null).filter(x => x != null);
        //il pezzo commentato fa la stessa cosa della riga sopra
        /*intestColonne.reduce((acc, curr, i) => {
        if (curr === 'importo') acc.push(i);
            console.log(acc);
            return acc;
        }, []);*/
        //leggo ogni colonna
        var movimenti=[];
        $('.tbi > tbody  > tr').each(function(index, tr) { 
            var movimento = [];
            $(this).find('td').each(function(index,td){
                if(index<cols){
                    movimento[intestColonne[index]] = $(this).text();
//here I have to add something to manage the duplicate indexes that are stored in the importi const                             
                }else{
                    movimento['causale']= $(this).children('select').val();
                    movimento['segno']= $(this).children('select').find(':selected').data('segno');
                }
            });
            movimenti.push(movimento);
        });
        console.log(movimenti);
    });

第二行的结果如下所示

Array []
​​    causale: "3"
​​    data_cont: "19/01/2021"
​​    data_val: "19/01/2021"
​​    descr: "PRELIEVO BANCOMAT"
​​    importo: "-50"
​​    length: 0
​​    segno: "-"

而实际上对于第一行来说

0: Array []
​​    causale: "3"
​​    data_cont: "19/01/2021"
​​    data_val: "19/01/2021"
​​    descr: "PRELIEVO BANCOMAT"
​​    importo: ""
​​    length: 0
​​    segno: "-"

我想输入"100"
一个三个三个一个
如果运行上面的代码段,结果将是只有最后一行有"Importo"的值,其他所有行都没有值。第一行中的250.0将被第二个空的"Importo"列覆盖

smdnsysy

smdnsysy1#

根据我的理解,当你移动到下一个单元格时,你想要获取单元格的文本值,除非它是空的,并且已经有一个非空的值用于这个标题。

movimento[intestColonne[index]] = $(this).text();

应该成为

var oldText = movimento[intestColonne[index]];
var newText = $(this).text();
if (newText || !oldText) movimento[intestColonne[index]] = newText;
0yg35tkg

0yg35tkg2#

我自己找到了解决办法:

$(this).find('td').each(function(index,td){
                if(index<cols){
                    if(importi.includes(index)){
                        if($(this).text()!=''){
                            movimento[intestColonne[index]] = $(this).text();
                        }
                    }else{
                        movimento[intestColonne[index]] = $(this).text();
                    }
                }else{
                    movimento['causale']= $(this).children('select').val();
                    movimento['segno']= $(this).children('select').find(':selected').data('segno');
                }
            });

如果我在标记为“Importo”if(importi.includes(index)){的列上,并且单元格if($(this).text()!=''){不为空,那么我将压入值。否则我将跳过单元格。我已经想到了这一点,但之前无法将其写在代码中。

cig3rfwq

cig3rfwq3#

别误会我的意思,但我还是不明白你的解释。
不过我还是写了这段代码,我希望它能帮助你(?)

const
  TbHead = document.querySelector('table.tbi thead')
, TbBody = document.querySelector('table.tbi tbody')
  ;
btMergeCols.onclick =_=>
  {
  let cols = [...TbHead.querySelectorAll('th select[name^="tipo_mov"]' )]
    .map( selec => ({ lib:selec.value, col: selec.closest('th').cellIndex, smovN: selec.name }))
    .sort( (a,b)=> b.lib.localeCompare(a.lib) || b.col-a.col); // simplify test order.

  //console.log( JSON.stringify(cols,0,2)); 

  cols.forEach( (curElm,i,{[i+1]:nxtElm}) => 
    {
    if (!!nxtElm && curElm.lib===nxtElm.lib )
      {
      TbHead.rows[0].deleteCell(nxtElm.col);     console.log( `${curElm.smovN} (${curElm.lib}) is removed (duplicate)` );

      for (let r = 0; r < TbBody.rows.length; r++) 
        {
        let CurVal = TbBody.rows[ r ].cells[ curElm.col ].textContent.trim();

        if (CurVal !== '')
          TbBody.rows[ r ].cells[ nxtElm.col ].textContent = CurVal;

        TbBody.rows[r].deleteCell(curElm.col);
        }
      }
    })
 
  // create array part
  let movimenti = []
    , finalCols = [...TbHead.querySelectorAll('th select[name^="tipo_mov"]' )]
        .map( selec => ({ lib:selec.value, col: selec.closest('th').cellIndex }))
    ;
  [...TbBody.rows].forEach( row => 
    {
    let elm = {};
    movimenti.push(elm);
    finalCols.forEach( ({lib,col})=>
      {
      elm[lib] = row.cells[col].textContent.trim();
      });
    });

  console.log( JSON.stringify(movimenti,0,2 ));
  }
body {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 14px;
  margin      : 1rem;
  }
table {
  border-collapse  : separate;
  border-spacing   : 1px;
  background-color : lightslategrey;
  }
tr { background-color: cadetblue;  }
td { background-color: whitesmoke; padding: .2em .5em; }
<button id="btMergeCols"> merge duplicates columns / create array </button>
<br><br>

<table class="tbi">
  <thead>
    <tr>
      <th>
        <select name="tipo_mov0">
          <option value="">Tipo campo</option>
          <option value="data_val" selected>Data Valuta</option>
          <option value="data_cont">Data Cont</option>
          <option value="descr">Descrizione</option>
          <option value="importo">Importo</option>
        </select> <i class="fas fa-trash-alt bin"></i></th>
      <th>
        <select name="tipo_mov1">
          <option value="">Tipo campo</option>
          <option value="data_val">Data Valuta</option>
          <option value="data_cont" selected>Data Cont</option>
          <option value="descr">Descrizione</option>
          <option value="importo">Importo</option>
        </select> <i class="fas fa-trash-alt bin"></i></th>
      <th>
        <select name="tipo_mov2">
          <option value="">Tipo campo</option>
          <option value="data_val">Data Valuta</option>
          <option value="data_cont">Data Cont</option>
          <option value="descr" selected>Descrizione</option>
          <option value="importo">Importo</option>
        </select> <i class="fas fa-trash-alt bin"></i></th>
      <th>
        <select name="tipo_mov4">
          <option value="">Tipo campo</option>
          <option value="data_val">Data Valuta</option>
          <option value="data_cont">Data Cont</option>
          <option value="descr">Descrizione</option>
          <option value="importo" selected>Importo</option>
        </select> <i class="fas fa-trash-alt bin"></i></th>
      <th>
        <select name="tipo_mov5">
          <option value="">Tipo campo</option>
          <option value="data_val">Data Valuta</option>
          <option value="data_cont">Data Cont</option>
          <option value="descr">Descrizione</option>
          <option value="importo" selected>Importo</option>
        </select> <i class="fas fa-trash-alt bin"></i></th>
      <th>Causale</th>
    </tr>
  </thead>
  <tbody>
    <tr class="text-info">
      <td>19/01/2021</td>
      <td>19/01/2021</td>
      <td>PRELIEVO BANCOMAT</td>
      <td>250.0</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>19/01/2021</td>
      <td>16/01/2021</td>
      <td>PAGAMENTO POS </td>
      <td>60.0</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>19/01/2021</td>
      <td>16/01/2021</td>
      <td>PAGAMENTO POS </td>
      <td>42.0</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>15/01/2021</td>
      <td>15/01/2021</td>
      <td>ADDEBITO SDD</td>
      <td>1501.2</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>15/01/2021</td>
      <td>13/01/2021</td>
      <td>PAGAMENTO POS </td>
      <td>167.31</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>11/01/2021</td>
      <td>06/01/2021</td>
      <td>PAGAMENTO UTENZE</td>
      <td>20.0</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>08/01/2021</td>
      <td>05/01/2021</td>
      <td>PAGAMENTO POS </td>
      <td>7.88</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>07/01/2021</td>
      <td>06/01/2021</td>
      <td>PRELIEVO BANCOMAT</td>
      <td>250.0</td>
      <td></td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
    <tr class="text-info">
      <td>05/01/2021</td>
      <td>05/01/2021</td>
      <td>BONIFICO</td>
      <td></td>
      <td>900.0</td>
      <td class="text-danger">
        <select name="causali">
          <option value="">Scegli</option>
          <option value="1" data-segno="+">Stipendio</option>
          <option value="2" data-segno="-">Rata Mutuo</option>
          <option value="3" data-segno="-">Saldo carta di credito</option>
          <option value="4" data-segno="+">Interessi Attivi</option>
          <option value="5" data-segno="-">Interessi Passivi</option>
          <option value="9" data-segno="-">Spese banca</option>
          <option value="10" data-segno="-">giro a c/famiglia</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>

相关问题