29

I want to define an associative array like this

var theVar = [
  { "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:

theVar["100"] = [0, 1, 2];
theVar["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.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Goro
  • 9,919
  • 22
  • 74
  • 108

2 Answers2

36
theVar = {
  "100": [0, 1, 2],
  "101": [3, 4, 5]
}

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

(As var is also a keyword in JavaScript, using it as a variable name is very likely to cause problems.)

MvanGeest
  • 9,536
  • 4
  • 41
  • 41
6

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
  • 7,693
  • 3
  • 48
  • 49
  • 6
    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 May 27 '10 at 22:38
  • 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 May 28 '10 at 01:10
  • 1
    Take a look here: http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation – Akira Yamamoto Dec 11 '13 at 12:59