Search code examples
javascriptpropertiesobject-literal

How to return a default property of JS literal object?


One JS object is defined like this:

var obj = {
      key1 : {on:'value1', off:'value2'},
      key2 : {on:'value3', off:'value4'}
}

Is there a tricky way, to pick a default key1 on property, when the obj.key1 is passed without property?

var key1State = obj.key1; // I want to receive 'value1' here, not obj.key1{...}

Is it somehow generally possible to recognize in the object definition body which property (if at all) is passed/asked during the object call?


Solution

  • I'm not sure if this is what you need, but messing with valueOf or toString may be what you're looking for.

    For example:

    var obj = {
          key1 : {on:'value1', off:'value2', toString : function(){ return this.on; }},
          key2 : {on:'value3', off:'value4', toString : function(){ return this.on; }}
    }
    
    var key1State = obj.key1; // the object
    var key1StateStr = '' + obj.key1; // string "value1"
    obj.key1 == "value1"  // true
    obj.key1.toString() === "value1"  // true
    

    So if you were going to use the default value as a string somewhere this may be useful.