Get column key in function (data) { ... }
Get column key in function (data) { ... }
alterego
Posts: 8Questions: 3Answers: 0
in DataTables
We're trying to generate columns dynamically from a json array based on each property.
Is there a way to get the key in the function (data)
?
The problem that we're running into is that within the function (data) { ... }
, the key is only the last value of the array.
Is there any other way to get it?
Maybe using the name
property of the column?
for (var key in jsonSchema.properties) {
console.log(key);
columns.push({
title: jsonSchema.properties[key].title,
name: key,
data: function (data) {
console.log(key); //doesn't get the right key
console.log(data.properties[key]);
return data.properties[key];
}
})
};
This discussion has been closed.
Replies
You need to create a closure function that would retain the value even after your loop has finished.
A slightly easier way is probably to use jQuery.each which will more or less create a closure for you since its an anonymous function.
Allan
Thanks @allan. Now sure how that would work though. As we understand the problem, it seems to be that the
function (data)
, be it a closure or not, gets executed after the array is created and the key can't be sent as a parameter.We got the solution working by initializing the table and retrieving the settings for each column.
let currentCol = table.settings().init().columns
Then leveraging the hidden property
name
to store the key in the JSON array, we're able to map it to the correct column in thedata.properties[...]
array ->data.properties[currentCol[settings.col].name]