0

I'm trying to get the following to return the appropriate key but keep getting only 9. Help and thank you.

var strZip = "96161";

var regionCodes = {
4: '00501',    
4: '00544',    
4: '06390',    
2: '96161',    
2: '96162',
getKey: function(value){
    for(var key in this){
        if(this[key] == value){
            return key;
        }
    }
    return 9; // Default 9 if not found
    }
};

var zipKey = regionCodes.getKey(strZip);

I've also tried (and failed) with the variation that reads:

getKey: function(value){
    for(var key in this){
        if( this.hasOwnProperty( key) ) {
            if(this[key] === value){
                return key;
            }
        }
    }
    return 9; // Default 9 if not found
}
Pavlo
  • 43,301
  • 14
  • 77
  • 113
OzzyO
  • 23
  • 4
  • 2
    The second `2: '96162'` overwrites the first one. You can't have multiple "values" on the same "key" – blgt Jun 04 '15 at 11:03
  • Your code shows an object with duplicate property names. – user2182349 Jun 04 '15 at 11:03
  • You should either revert the map (having your values as keys) or use an array. – Denys Séguret Jun 04 '15 at 11:04
  • js does not have _associative array_, so when you define literal object - js no _push_ every property, but override same key with last value – Grundy Jun 04 '15 at 11:06
  • It's worth mentioning that Ecmascript 6 will actually support duplicate object keys, for some reason. – Jeremy Thille Jun 04 '15 at 11:10
  • @JeremyThille can you show where it, i mean link? it interesting how get values for that key :-) Or you mean support: not raise exception in strict mode? – Grundy Jun 04 '15 at 11:11
  • Argh, I can't find it back. I saw a post on stackoverflow yesterday, precisely about "what's the advantage of supporting duplicate object keys in ES6?", I'm searching the post – Jeremy Thille Jun 04 '15 at 11:19
  • Oh, here it is : http://stackoverflow.com/questions/30617139/whats-the-purpose-of-allowing-duplicate-property-names/30617831#30617831 – Jeremy Thille Jun 04 '15 at 11:20
  • @JeremyThille, so by link say that anyway you can get only last defined value, or i something missed? – Grundy Jun 04 '15 at 11:24

2 Answers2

7

You have identical keys {4:,4:,4:,2:,2:} in your object. Try making the keys unique or change your approach like in Andys answer.

Otherwise, it will only work if the value happens to be of the first key in the object

var strZip = "96161";

var regionCodes = {
1: '00501',    
2: '00544',    
3: '06390',    
4: '96161',    
5: '96162',
getKey: function(value){
    for(var key in this){
        if(this[key] == value){
            return key;
        }
    }
    return 9; // Default 9 if not found
    }
};

var zipKey = regionCodes.getKey(strZip);
console.log(zipKey);

Or use key -> array with indexOf() like

var strZip = "961261";

var regionCodes = {
4: ['00501', '00544',  '06390'],
2: ['96161', '96162'],
getKey: function(value){
    for(var key in this){
        if(typeof(this[key]) != 'function' && this[key].indexOf(value) > -1){
            return key;
        }
    }
    return 9; // Default 9 if not found
    }
};

var zipKey = regionCodes.getKey(strZip);
console.log(zipKey);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • would love an explanation for the downvote, pretty please? :) – AmmarCSE Jun 04 '15 at 11:10
  • Because it appears the actual keys are important otherwise the OP wouldn't have tried to specify more than one. You're returning the wrong keys. For example, you're returning `1` not `4`. – Andy Jun 04 '15 at 11:20
  • @Andy, OP said 'I'm trying to get the following to return the appropriate key but keep getting only 9.'... I explained why he is getting 9. If the actual keys are important he will need to try another approach such as your answer. I changed the keys to show his error, thats all – AmmarCSE Jun 04 '15 at 11:25
  • And you said: "Try making the keys unique." and that's not what the OP apparently wants. – Andy Jun 04 '15 at 11:27
  • @Andy, in which I said thereafter **Otherwise**, it will only work if the value happens to be of the first key in the object. Anyways, I appreciate your input, even if its a downvote. I was just concerned there may be something technically incorrect with my answer – AmmarCSE Jun 04 '15 at 11:30
  • Yes, that works! You-all were right in that I was duplicating keys and that the keys are important. I just need to re-structure things accordingly. Though the suggestion to reverse the keys and values would probably work too. Thank you all!!! – OzzyO Jun 04 '15 at 15:14
  • Actually, another problem now. If the value is found - no problem - but if it isn't, the value of 9 is not being returned. I tried changing "function (value)" to "function (value,def=9)" and then "return def" but it failed. I tried a routine after the var zipKey statement that checks for null and sets zipKey to 9 but that didn't work either. I modified the null routine to check for a range <1 or > 4 (the values returned from a successful check) and THAT didn't work either. How to get a return of 9 if the search doesn't succeed? – OzzyO Jun 04 '15 at 16:41
  • @OzzyO, what was happening is it was iterating through all properties of the object including the function. When it got to the function, it gave an exception of undefined indexOf for the function. If you check that you are not at the function l ike I did, you should be fine. Let me know if you need further assistance – AmmarCSE Jun 04 '15 at 16:49
  • AmmarCSE - Now I understand what's going on. Everything works fine. Thank you very much for your help. – OzzyO Jun 04 '15 at 16:54
3

Assuming that the keys are important and, unlike the other answers suggest, they are actually needed in the form you've put in your question, put your keys/codes in an array instead using an object for each group. Then you can use filter on the array to pluck out the correct key based on the code provided:

var regionCodes = {

    codes: [{
        key: 4, code: '00501'
    }, {
        key: 4, code: '00544'
    }, {
        key: 4, code: '06390'
    }, {
        key: 2, code: '96161'
    }, {
        key: 2, code: '96162'
    }],

    getKey: function (value) {
        var arr = this.codes.filter(function (el) {
            return el.code === value;
        });
        return arr.length ? arr[0].key : 9;
    }
};

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95