1

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 Answers 2

4

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'
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks patrick dw. Any other way to go about storing keys and values in array accessible by index in a similar fashion?
@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.
Beautiful. Look's like the former will do best for my needs. Thanks patrick!
0

Perhaps you can use a workaround if your application design allows it. It worked for me some times.

var defaults = {
    fileTypes : {
        0: {
          key: 'windows',
          file: 'Setup_File.exe'
        },
        1: {
          key: 'mac',
          file: 'Setup_File.dmg'
        }
    }
};

On that way you can access the first level elements by index (in that specific order) and if you need the keys from your example, they are still there.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.