Jquery / javascript index in collection / map property by object?

I have the following Javascript defining an array of countries and their states ...

var countryStateMap = [{"CountryCode":"CA","Name":"Canada","States":[{"StateCode":"S!","CountryCode":"CA","Name":"State 1"},{"StateCode":"S2","CountryCode":"CA","Name":"State 2"}]},"CountryCode":"US","Name":"United States","States":[{"StateCode":"S1","CountryCode":"US","Name":"State 1"}]}];

Depending on the country that the user selects, I need to update the selection options for the states from the selected Country object. I know that I can index into a collection of countries with an index int like this ...

countryStateMap[0].States

I need a way to get the Country by CountryCode property. I know the following does not work, but what I would like to do is something like this ...

countryStateMap[CountryCode='CA'].States

Can this be achieved without completely rebuilding my collection structure or repeating over the set each time to find the one I want?

UPDATE: I accepted mVChr's answer because it worked and was the easiest solution, even if it required a second card.

, , , . , . ...

countryStateMap[$('#country').attr("selectedIndex")]

, .

+3
3

, , - , :

var csmMap = {};
for (var i = 0, cl = countryStateMap.length; i < cl; i++) {
  csmMap[countryStateMap[i].CountryCode] = i;
}

, countryCode = 'CA', :

countryStateMap[csmMap[countryCode]].States
+6
countryStateMap.get = function(cc) {
    if (countryStateMap.get._cache[cc] === void 0) {
        for (var i = 0, ii = countryStateMap.length; i < ii; i++) {
            if (countryStateMap[i].CountryCode === cc) {
                countryStateMap.get._cache[cc] = countryStateMap[i];
                break;
            }
        }
    }
    return countryStateMap.get._cache[cc];
}
countryStateMap.get._cache = {};

.get("CA")

countryStateMap.get("CA").States

, underscore, ,

countryStateMap.get = _.memoize(function(cc) {
    return _.filter(countryStateMap, function(val) {
        val.CountryCode = cc;
    })[0];
});

_.memoize, _.filter

+2

love your local jQuery:

A small little function for you:

getByCountryCode = function (code) {var res = {}; $. each (countryStateMap, function (i, o) {if (o.CountryCode == code) res = o; return false;}); return res}

then do the following:

getByCountryCode ("CA"). States

and it returns:

[Object, object]

0
source

All Articles