Nicolas Aoki
Nicolas Aoki

Reputation: 78

How to rename certain JSON Object attribute to display it in HTML Table

If I have a list of objects acquired from a database

[{ "id":0 ,"name":"John", "lastname":"Shell" },{ "id":1,...];

which results in (dynatable plugin):

 data : JSON.stringify(data)
 success: function(data,status){ 
          $('#table').dynatable({
            dataset:{
              records:data
            }
          })
        }

but I don't want to show the id on 'th' when generating a table in the html, instead I want to rename it to securityNumber without changing the actual JSON

      <table id="tabela">
        <thead>
           <th>id</th>
           <th>name<th>
           <th>last_name<th>
        </thead>
      </table>

I can't just replace id because the plugin identifies the columns name through the attribute of the JSON Object

I've tryed different plugins, i'm using dynatable (already searched at the documentation) but I am open to another solution.

How do I proceed ?

Upvotes: 1

Views: 820

Answers (1)

Dom
Dom

Reputation: 1816

You can add a custom formatting method on textTransform and write up the mappings for the column names there. Check the docs here.

An example of such a method might be

dynatable.utility.textTransform.customColumnName = function(text) {
  if (text) === 'id' return 'security_number'
  return text
}

Alternatively, you can transform the array with Array.map without changing the source JSON, for example:

...
records: data.map((item) => {
  return {
    security_number: item.id,
    name: item.name,
    last_name: item.last_name
  }
}),
...

Upvotes: 1

Related Questions