Dynamic creation of multilevel Javascript object f

2019-04-09 21:58发布

问题:

jTable (jTable.org) layout is defined by the code below. I want to build it dynamically (based on AJAX return from a database query).

{
    title: 'My Dynamic Title',
    fields: {
        id: {
            title: 'ID'
        },
        salesperson: {
            title: 'Salesperson'
        },
        pivot1: {
            title: '2012-01'
        },
        pivot2: {
            title: '2012-02'
        },
        pivot3: {
            title: '2012-03'
        }
    }
}    

The data being displayed is a pivot table and so the number of columns and their titles will change. Is it possible for me to dynamically modify the fields section above? e.g., to have four pivot columns with relevant column titles.

Answer

I figured it out thanks to Barmar and extensive reading. The trick is to insert a new object at each level. Pop this into jsfiddle.net and you can see the result. It will programmatically create the object above.

var myobj = {}; //description for jquery-jtable configuration.
var colnames = ['pivot1', 'pivot2', 'pivot3'];
var titles   = ['2012-01', '2012-02', '2012-03'];

myobj['title'] = "My Dynamic Title";
myobj['fields'] = {};                     //create a second level under 'fields'.
myobj.fields['id'] = {title: 'ID'};
myobj.fields['salesperson'] = {title: 'Salesperson'};
for(i = 0; i < colnames.length; i++) {
    myobj.fields[colnames[i]] = {};       //create a third level under column name.
    myobj.fields[colnames[i]].title = titles[i];
}
alert(JSON.stringify(myobj, null, 4));

回答1:

I don't see a method to change the field specification dynamically. But if you're modifying the table, you can simply destroy the old jTable and reinitialize it:

$("#TableContainer").jtable("destroy");
$("#TableContainer").jtable({
    // New options
});

If there are some options that will stay consistent across all instances, you can use a variable to hold the options:

var jtable_options = {
    title: "My Table Title",
    fields: {}
};

Before you initialize a jtable, you do:

jtable_options.fields = {
    id: { title: 'ID' },
    salesperson: { title: 'Salesperson' }
    ...
};
$("#TableContainer").jtable(jtable_options);