Get column key in function (data) { ... }

Get column key in function (data) { ... }

alteregoalterego Posts: 8Questions: 3Answers: 0

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];
        }
    })
};

Replies

  • allanallan Posts: 63,368Questions: 1Answers: 10,449 Site admin

    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

  • alteregoalterego Posts: 8Questions: 3Answers: 0

    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.

  • alteregoalterego Posts: 8Questions: 3Answers: 0
    edited July 2018

    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 the data.properties[...] array -> data.properties[currentCol[settings.col].name]

    for (var key in jsonSchema.properties) {
        columns.push({
            title: jsonSchema.properties[key].title,
            name: key, 
            data: function (data, type, ignored, settings) {
                let currentCol = table.settings().init().columns;
                let val = data.properties[currentCol[settings.col].name];
                return (val) ? val : "";
            }
        })
    };
    
This discussion has been closed.