How to automatically add properties to an object that is undefined?
You can use the Logical nullish assignment (??=):
var test = {};
(test.hello ??= {}).world ??= "Hello doesn't exist!";
var test = {};
test.hello = test.hello || {};
test.hello.world = "Hello world!";
If test.hello
is undefined, it gets set to an empty object.
If test.hello
was previously defined, it stays unchanged.
var test = {
hello : {
foobar : "Hello foobar"
}
};
test.hello = test.hello || {};
test.hello.world = "Hello World";
console.log(test.hello.foobar); // this is still defined;
console.log(test.hello.world); // as is this.
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!