3

Is there a way to access an JavaScript object like this:

var a = {};
a.propertyA.propertyB;

where a.propertyA is of course undefined, but I'd like to write a.propertyA.propertyB assuming a.propertyA is not undefined. If a.propertyA is undefined, I expect a.propertyA.propertyB also to be undefined.

I'm developing with complicate objects, so sometimes I feel like accessing objects with multiple properties at once. I wonder there's a kind of get method that can be given a default value.

Thank you in advance.

tsuda7
  • 413
  • 1
  • 6
  • 25

2 Answers2

1

There is absolutely no way to do this without using string literals first, to ensure it exists, or create the chain if necessary.

/**
 * Define properties to be objects on a root object if they dont' exist
 *
 * @param o the root object
 * @param m a chain (.) of names that are below the root in the tree
 */
function ensurePropertyOnObject(o, m)
{
    var props = m.split('.');
    var item;
    var current = o;

    while(item = props.shift()) {
        if(typeof o[item] != 'object') {
            current[item] = {};
        }
        current = o[item];
    }    
}

var a = new Object
ensurePropertyOnObject(a, "propertyA.propertyB");
a.propertyA.propertyB = "ho";
console.log(a);
Ryan
  • 14,392
  • 8
  • 62
  • 102
-1

try using something like this:

function get(a){
    if (a.propertyA === undefined){
        a.propertyA = {propertyB: undefined};
    }
    else{
        //do whatever with a.propertyA.propertyB
    }
    return a; //or whatever you'd like to return
}
holtc
  • 1,780
  • 3
  • 16
  • 35