Set column data

Set column data

N0tChrisN0tChris Posts: 7Questions: 0Answers: 0

Hi,
I'm trying to copy values of selected column to the previous one like that :

function copyColumnLeft(currentColumn, prevColumn) {
  const currentColumnData = currentColumn.data()
  const currentColumnIndex = currentColumn.index()
  if (currentColumnIndex < 1) {
    return
  }
  // Here, I'm trying to copy current column data in previous column but it doesn't work...
  prevColumn.data(currentColumnData).draw() 
}

This way doesn't work and I didn't find on forums and documentation a great solution to copy values from a column to another...

Thanks for your help!

Replies

  • kthorngrenkthorngren Posts: 15,821Questions: 25Answers: 3,751

    The column().data() docs state this:

    This method is used to get the data used for the cells in the column matched by the selector from DataTables.

    So its just a getter.

    Datatables doesn't have any API's to bulk copy data from one column to another. You will need to loop through the rows using rows().every() then copy the data in the loop. Don't use draw() in the loop. After the loop use draw() so the table is drawn only once.

    Kevin

  • kthorngrenkthorngren Posts: 15,821Questions: 25Answers: 3,751

    Another option is to use the ColReorder extension. You can use the colReorder.move() move the columns. Not sure that is what you want though.

    Kevin

  • N0tChrisN0tChris Posts: 7Questions: 0Answers: 0

    Thank you for your answer!

    I'm trying to apply your solution but I get another problem :

    function copyColumnLeft(table, currentColumn, withCodem) {
      var currentColumnIndex = currentColumn.index()
      if (currentColumnIndex < 1) {
        return
      }
      const currentVx = 'v' + currentColumnIndex / 3
      const prevVx = 'v' + ((currentColumnIndex / 3) - 1)
    
      let values = []
      table.rows().every(function () {
        const data = this.data()
        if (data[currentVx]) {
            values.push(withCodem ? data[currentVx]: data[currentVx].dem);
        }
        if (data[prevVx]) {
          // Here, I want to change values of data[prevVx] but I don't know how... 
          console.log(data[prevVx].dem);
        }
      })
    }
    

    I don't if I should use draw or an other DataTables function to change column values.

  • kthorngrenkthorngren Posts: 15,821Questions: 25Answers: 3,751

    I'm not sure what you are trying to do in that function. Here is a simple example of copying one column to the other:
    http://live.datatables.net/detameqi/1/edit

    Click the button to copy the Office column to the Position column. Is this what you are trying to do?

    Kevin

  • N0tChrisN0tChris Posts: 7Questions: 0Answers: 0
    edited January 14

    Thank you for your perfect answer.

    It fits perfectly with my needs!

    Thanks again!

Sign In or Register to comment.