0

In Javascript, I'd like to have an object with three properties, "zone1", "zone2", "zone3", each of which store an array of place names. I would like to search for a match by iterating through the arrays to find a place name. The following questions almost gets me there, but don't work for me because I am not using jQuery, and I want the value, not the key:

My code looks like this:

var zoneArray = {};
zoneArray["zone1"] = ["placeA", "placeB"];
zoneArray["zone2"] = ["placeC", "placeD"];

function getZone(place, zoneArray) {
    var zone;
    for (var key in zoneArray) {
        for(i = 0; i<key.length; i++) {
            if(key[i] == place) {
                zone = key;
                return zone;
            }
        }
    }

}
getZone("placeC", climateZoneArray);

Apparently however, "key[i]" is referring to letters of the zone names, like, "z" "o" "n" "e"

Could anybody please help me understand or best handle this situation in Javascript?

Community
  • 1
  • 1
bryant
  • 2,041
  • 3
  • 18
  • 26

2 Answers2

4

Use zoneArray[key] to access the array.

for (var key in zoneArray) {
    var arr = zoneArray[key]
    for(i = 0; i<arr.length; i++) {
        if(arr[i] == place) {
            zone = key;
            return zone;
        }
    }
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Using for ... in to iterate over an object's properties can lead to some pretty surprising results, especially if you're working in an environment where Object.prototype has been extended. This is because for ... in will iterate over an objects enumerable properties and the enumerable properties contained in that objects prototype chain. If this isn't what you want but you are going to use for ... in anyways, it's recommended to have a conditional statement at the top of the loop that checks that the property belongs to the object which is being iterated over. (if (!foo.hasOwnProperty(x)) continue;). Luckily, there is Object.keys(). You can use Object.keys() to get an array of an objects own enumerable properties, if you do this you can skip hasOwnProperty ugliness. Instead of iterating over the object you can iterate over an array of it's keys.

var collection = {
    zone1: ['placeA', 'placeB'],
    zone2: ['placeC', 'placeD']
};

function getZone(needle, collection) {
    var zones = Object.keys(collection),
        found;
    for (var i = 0, l = zones.length; i < l; i++) {
        found = collection[zones[i]].filter(function(place) {
            return needle == place;
        });
        if (found.length > 0) {
            return zones[i];
        }
    }
};

console.log(getZone('placeC', collection));

This is also here on jsfiddle.net

One last thing, be very careful when creating variables, in the inner for loop you created the variable i without using the var keyword. This resulted in i being bound to the global context, something you really want to avoid.

Colin
  • 852
  • 7
  • 6