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
You won't be able to do this without some sort of function, as JavaScript doesn't have a generic getter/setter method for objects (Python, for example, has __getattr__). Here's one way to do it:
function add_property(object, key, value) {
var keys = key.split('.');
while (keys.length > 1) {
var k = keys.shift();
if (!object.hasOwnProperty(k)) {
object[k] = {};
}
object = object[k];
}
object[keys[0]] = value;
}
If you really want to, you could add it to the prototype of Object. You can call it like so:
> var o = {}
> add_property(o, 'foo.bar.baz', 12)
> o.foo.bar.baz
12