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.

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

This is the way to create the js-version of an associative array. It's called Object Literal Notation.
need a variable after "var" or change array name to a not reserved word
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

3 Comments

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. ;)
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?

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.