How to retrieve data by name when using plain HTML as data source?

How to retrieve data by name when using plain HTML as data source?

bellons91bellons91 Posts: 2Questions: 1Answers: 0

Hi there,

I'm using a Datatable basing on plain HTML table (without JSON or similar), just like the "zero configuration" in the examples.

How can I read data from a cell using column name and not position?

I've created this jsfiddle as example: https://jsfiddle.net/oo743w7v/1/

As you can see, the result of the data is a simple array. I need to read data using column name, because in the future I will add, move or delete columns, so I don't want to change every time the code to update the position of a column.

Thank you all ;)

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395
  • rduncecbrduncecb Posts: 125Questions: 2Answers: 28

    You can also use the column name in a column-selector, for example, the get all the data in the table for a given row by column name

    table.column('mycolumnname:name').data();
    
  • kthorngrenkthorngren Posts: 21,174Questions: 26Answers: 4,923

    Looks like column().name() is available in Datatables 2.0 and not 1.10:

    Since: DataTables 2.0.0

    Kevin

  • bellons91bellons91 Posts: 2Questions: 1Answers: 0

    Woah, I was misunderstood.
    I need to retrieve data from a single row, given the index row.
    Then I need to use the object returned by
    row(index).data()

    for some calculations.

    So I don't need just the data of all the column, but I need to retreve the object with the properties corresponding to the columns' names.

    In the example provided in the question, you can see the JSON of the object returned by the data() call. It is a simple array.

    I noticed that using the same code to retrieve data, but setting the input of the table by JSON and not plain HTML, I get an object with the properties required.

    I'm looking for a method to have the object corresponding to the single row.

  • kthorngrenkthorngren Posts: 21,174Questions: 26Answers: 4,923

    As you probably know when using row().data() with DOM sourced data the return will be an array. There may be one but I don't know of an easy way around this using Datatable API's.

    One option may be to build a variable the contains the column names and positions, something like this:

    columnNames = {
      'Name': 0,
      'Position': 1,
      'Office': 2,
     }  
    

    Then tack that on to row.data(), something like this:
    $("#result").append(JSON.stringify( dtExample.row(5).data()[columnNames['Position']]));

    Maybe someone will post a better option.

    Kevin

This discussion has been closed.