2

I'm building my first jQuery plugin. It takes JSON data and loads it into table. I've got most of the logic done, I'm just having trouble building the default options array.

What I would like to do is pass in an options array like this:

/* Column array format:
    cols:
    [colname:
    {
        title: 'Column Title',  // Column title for display (if not specified, will
                                // use 'colname' value instead.
        sorttype: 'text',       // 'text', 'dropdown' or 'none'
    },
    nextcolname:
    {
        ...
    },
    ...
    ]
*/

What I'm having problems with is packing the default array if no options are passed in. Here's what I have:

var settings = $.extend ({
    'cols'      : 'auto',
    'sortable'  : 'true' //turn off sorting altogether with this option.
}, options);

var index = '';
var element = '';
var colname = '';

// No columns specified.  That's OK, grab keys from first JSON element.
if (settings.cols == 'auto')
{
    settings.cols = Object.keys(data[0]); 

    $.each(settings.cols, function(index, colname){
        settings.cols[colname].title = colname;
        settings.cols[colname].sorttype = 'text';
    })
}

First of all, style-wise, does it look like I'm going about this the right way? Do both the format of the options array and the way I'm parsing it make sense? Second of all, the settings.cols[colname].title returns a type error because it doesn't exist (of course). How do I populate this object so I can use it effectively so that I can iterate through it?

1 Answer 1

2

The line where you assign settings.cols isn't going to work ... it assigns an array rather than a property map. Try this instead:

var keys = Object.keys(data[0]);
for (var i in keys) settings.cols[keys[i]] = {};

Here's a complete test that shows the difference. settings1 comes out valid using the above, but trying to access settings2 throws an error:

var data = { a: 1, b: 2, c: 3 };
var keys = Object.keys(data);
var settings1 = { cols: {} };
var settings2 = { cols: {} };
for (var i in keys) settings1.cols[keys[i]] = {title: "hi"};
settings2.cols = Object.keys(data);
alert(settings1.cols["b"].title);
alert(settings2.cols["b"].title);
Sign up to request clarification or add additional context in comments.

1 Comment

Aha, that's the leap of logic I wasn't making. You can't go from array to property map. I'll try it that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.