Search code examples
javascriptobjectprototypejsundefined

Return different values instead of undefined when key isn't found in an object


I'd like to set a property to an object using prototype, if it's possible, so that when I try to get an undefined value, it returns a default instead of undefined, like:

obj = {
  lang : {en: 'hello', it:'ciao'}
}

Example 1: obj.lang.es (undefined) - I'd like to get obj.lang.en instead of undefined.

Example 2: obj.something.else - I'd like to get false instead of an error because it can't read else of undefined.


Solution

  • It is probably not a good idea. Better use a root or default key:

    obj = {
        lang : {root: 'hello', en: 'hello', it:'ciao'}
    }
    

    So you can ask for a lang in this way:

    var hi = obj.lang.es || obj.lang.root;
    

    You can use this in combination with a getter method:

    var getTranslation = function(lang) {
        return obj.lang[lang] || obj.lang.root;
    };
    var hi = getTranslation("es");