views:

77

answers:

2

Hello,

I want to define an associative array like this

var = [
  { "100", [0, 1, 2] },
  { "101", [3, 4, 5] }
]

Essentially I want to be able to access an array of three numbers by specifying the custom index.

However, no matter what I try I cannot make it work.

I know I can define it as:

var["100"] = [0, 1, 2];
var["101"] = [1, 2, 3];

but I am setting this somewhere else and I'd prefer to be able to set it in a single statement.

Thanks,

+8  A: 
var = {
  "100": [0, 1, 2],
  "101": [3, 4, 5]
}

might do the trick. You can then access using var["101"] (or var[101] for that matter)

MvanGeest
This *is* the way to create the js-version of an associative array. It's called Object Literal Notation.
Sean Kinsey
+3  A: 

Have a look at the JSON syntax, I think It could inspire the building of your data structures in a way that will be flexible, correct and complex as you want.

This page has a lot of information and example that are helpful for you.

For instance look at this:

var employees = { "accounting" : [   // accounting is an array in employees.
                                    { "firstName" : "John",  // First element
                                      "lastName"  : "Doe",
                                      "age"       : 23 },

                                    { "firstName" : "Mary",  // Second Element
                                      "lastName"  : "Smith",
                                      "age"       : 32 }
                                  ], // End "accounting" array.                                  
                  "sales"       : [ // Sales is another array in employees.
                                    { "firstName" : "Sally", // First Element
                                      "lastName"  : "Green",
                                      "age"       : 27 },

                                    { "firstName" : "Jim",   // Second Element
                                      "lastName"  : "Galley",
                                      "age"       : 41 }
                                  ] // End "sales" Array.
                } // End Employees
microspino
This is is not JSON. This is Object Literal Notation - JSON is a **subset** of this.The first premise of being able to call anything JSON is that it is contained in a **string**. ;)
Sean Kinsey
Looks like JSON to me. Property names must be strings to be proper JSON, but the values do not. Or is there something else you mean?
rob