I have an object called MyObject
and a method called createEntry()
which aims to create a new property for MyObject
and sub-properties for the property or just skip it altogether if it already exists.
My code:
var MyObject = {
createEntry: function (val1, val2, val3, val4) {
this[val1] = this[val1] || {};
this[val1][val2] = this[val1][val2] || {};
this[val1][val2][val3] = val4;
}
};
MyObject.createEntry("val1", "val2", "val3", "val4");
As shown in the above function, I'm trying to create a new sub-object for each argument of the method createEntry()
except for the last two, where val3
is a property
or method
and val4
is its value.
With my method in its current state, I can only reach up to level 3 with its subsequent ones requiring longer and longer code. I assume the above can be achieved with a while
loop, but I haven't been able to figure it out yet.
Question: How can I create unlimited sub-objects based on the number of arguments passed on the above function in a tree fashion that looks like the following:
var MyObject = {
val1: {
val2 {
val3: val4
}
}
}