let say I want to do this:
var dashboard = {};
var page = \"index\";
$(\'.check\').click(function(){
$(thi
I don't think there's a good builtin way to do this, but you could always abstract it with a function.
function getProperty(obj,prop){
if( typeof( obj[prop] ) == 'undefined' ){
obj[prop] = {};
}
return obj[prop];
}
Then you use
getProperty(dashboard,'pages')['pagename']
or
getProperty(getProperty(dashboard,'pages'),'pagename');
As mentioned, $.extend will make this less burdensome.
Well I guess you need this:
var dashBoard = new Array();
if(!dashboard['page123']) {
dashBoard.push('page123');
} else {
...do what you want
}
Seems you are dealing with XML.
If you use underscore >= 1.9.0, you can use property and propertyOf:
d={a: {b: "c"}}
_.property(["a", "b", "c", "e"])(d) // undefined
_.property(["a", "b"])(d) // "c"
_.propertyOf(d)(["a", "b", "c", "e"]) // undefined
_.propertyOf(d)(["a", "b"]) // "c"
var foo = dashboard['pages'] || {};
foo['pagename'] = 'your thing here';
dashboard['pages'] = foo;
Explaining: the first line will check if the first value is null, undefined or... false (don't think this is a problem here): if it is, create a new object, if it is not, will use it.
I would do it with the ternary operator:
dashboard['pages'][page] = dashboard['pages'][page] ? dashboard['pages'][page] : {};
That will do the trick no matter if it's set/null or whatever.
The best solution for my case was to do a Object prototype
/**
* OBJECT GET
* Used to get an object property securely
* @param object
* @param property
* @returns {*}
*/
Object.get = function(object, property) {
var properties = property.split('.');
for (var i = 0; i < properties.length; i++) {
if (object && object[properties[i]]) {
object = object[properties[i]];
}
else {
return null;
}
}
return object;
};
And then you can get your property like this
var object = { step1: { step2: { step3: ['value1', 'value2'] }}}
Object.get(object, 'step1.step2.step3'); // ['value1', 'value2']
Object.get(object, 'step1.step2.step3.0'); // 'value1'
Object.get(object, 'step1.step2.step3.step4'); // null
Hope it helps :)