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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With