Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: accessing an object with properties which can be undefined [duplicate]

Tags:

javascript

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.

like image 229
tsuda7 Avatar asked Aug 07 '26 17:08

tsuda7


1 Answers

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);
like image 85
Ryan Avatar answered Aug 09 '26 07:08

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!