views:

28

answers:

1

Hello, using jQuery, I'm trying to get values of fileTypes by using an index. I'm not sure how to do go about doing this but so far I've tried settings.fileTypes[0] which does not work. Any help is appreciated, thanks!

    var defaults = {
        fileTypes : { 
            windows: 'Setup_File.exe',
            mac: 'Setup_File.dmg',
            linux: 'Setup_File.tar.gz',
            iphone: 'iPhone App'
        }
    },
        settings = $.extend({}, defaults, options);
+2  A: 

fileTypes is an Object, and as such, its properties can not be access via index number.

Objects do not guarantee any defined order, so if you need to maintain items in an indexed order, you would need to use an Array instead.

To get the first item given your example, you would do so by name:

settings.fileTypes.windows;  // will return 'Setup_File.exe'

To store as an Array whose items you can retrieve by index, try this:

var defaults = {
        fileTypes : [
            'Setup_File.exe',
            'Setup_File.dmg',
            'Setup_File.tar.gz',
            'iPhone App'
        ]
    },

settings.fileTypes[0];  // will return 'Setup_File.exe'

Or you could do an Array of Objects, though I don't think that's what you're after:

var defaults = {
        fileTypes : [ 
            {type: 'Setup_File.exe'},
            {type: 'Setup_File.dmg'},
            {type: 'Setup_File.tar.gz'},
            {type: 'iPhone App'}
        ]
    },

settings.fileTypes[0].type;  // will return 'Setup_File.exe'
patrick dw
Thanks patrick dw. Any other way to go about storing keys and values in array accessible by index in a similar fashion?
Ryan
@Ryan - you would need to use an Array instead of an Object. You could also use an Array of objects if you need. I'll update my answer with both those examples.
patrick dw
Beautiful. Look's like the former will do best for my needs. Thanks patrick!
Ryan
@Ryan - You're welcome. :o)
patrick dw