-3

how would you define an array in JavaScript like the one below and retrieve values by doing a search for country and gets the list of region.

region['US'] = {'Region 1': 'East', 'Region 2': 'West'}
user2120021
  • 25
  • 1
  • 4
  • 2
    You have listed an object, not an array. In JavaScript, arrays with string keys are always objects. – Lix Apr 30 '13 at 17:53
  • [JavaScript doesn't have associative arrays, but you can create an abstract object](http://stackoverflow.com/q/1098040/901048) which basically behaves the same way. – Blazemonger Apr 30 '13 at 17:54
  • You would need to use JSON and JSON's dot notation to retrieve data. – Scott Sword Apr 30 '13 at 17:54
  • 1
    @Lix: All keys in JavaScript are strings... just to be clear. All arrays are always objects. –  Apr 30 '13 at 17:55
  • @squint if it is an `Array` then the `keys` are just the index in the array. That's what he is talking about. – Daniel Moses Apr 30 '13 at 17:56
  • @squ - `var a = ['foo','bar']; var index=0; index++; console.log(a[index])`. Or am I missing something? – Lix Apr 30 '13 at 17:56
  • @Lix Only that `index` is converted to a string when used in the `[]` operator. Using `"0"` would work just the same. –  Apr 30 '13 at 17:57

2 Answers2

1

You want an object, not an array. Objects have string keys, arrays have numeric keys only.

var region = {
  US: {'Region 1': 'East', 'Region 2': 'West'},
  UK: {'Region 1': 'East', 'Region 2': 'West'}

}

then get it with

region['US']

or

region.US
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
0

If we declare specific classes for the Country and the Region, this should work:

var Region = function(data) {
 var self = this;
 self.name = data.name || "";
}

var Country = function(data) {
 var self = this;
 self.name = data.name || "";
 self.regions = new Array();
}

var countries = {};
countries["US"] = new Country({ "name" : "US" });
countries["US"].regions.push(new Region({ "name" : "Region 1"}));
countries["US"].regions.push(new Region({ "name" : "Region 2"}));
Jalayn
  • 8,934
  • 5
  • 34
  • 51