So I have a JavaScript function that gets an object and has a precreated object. The goal is that the function adds all missing properties of the passed object to the precreated one.
When just comparing one level, this is easy. For example in order to achieve this:
Precreated: {hello: "world"}
Passed: {hello: "there", colour: "green"}
Result: {hello: "world", colour: "green"}
You just look over each key of the passed object, look if that key already exists in the precreated one, and if not, add it with the respective value.
However, if you want to do this with multiple levels it kinda gets weird. For example, I want this to work:
Precreated: {hello: {there: true}}
Passed: {hello: {world: true}}
Result: {hello: {there: true, world: true}}
My idea was that I would just loop over the passed object, and if I find an object inside, call the function again with that object, and so on until all children were processed by the function.
When you do that, however, you would have to compare the children of both objects dynamically. Say, I know in the programme how many levels deep it is, what the key is called and so on, how do I programmatically access it?
I'm asking because I can't hardcode something like if (result[key1][key2][key3]...
, and something like if (result[keys.join(..)]...
isn't possible as well I think.
So how do I programmatically access a property of an object which is multiple levels deep, not knowing how deep at the time of writing the code?