Is there an easy way to automatically add properties to objects if they don\'t allready exist?
Consider the following example:
var test = {}
test.hel
New object
myObj = {};
recursive function
function addProps(obj, arr, val) {
if (typeof arr == 'string')
arr = arr.split(".");
obj[arr[0]] = obj[arr[0]] || {};
var tmpObj = obj[arr[0]];
if (arr.length > 1) {
arr.shift();
addProps(tmpObj, arr, val);
}
else
obj[arr[0]] = val;
return obj;
}
Call it with a dot notated string
addProps(myObj, 'sub1.sub2.propA', 1);
or with an array
addProps(myObj, ['sub1', 'sub2', 'propA'], 1);
and your object will look like this
myObj = {
"sub1": {
"sub2": {
"propA": 1
}
}
};
It works with non-empty objects too!