I have a JavaScript function that takes an object and a pre-existing object. The objective is for the function to add all missing properties from the passed object to the pre-existing one.
While this process is simple when comparing on a single level, it becomes more complex with multiple levels. My goal is something along these lines:
Pre-existing: {hello: "world"}
Passed: {hello: "there", colour: "green"}
Result: {hello: "world", colour: "green"}
The method involves examining each key of the passed object. If the key does not exist in the pre-existing object, it is added with its corresponding value.
However, extending this functionality to handle multiple levels presents challenges. For example, consider the scenario where:
Pre-existing: {hello: {there: true}}
Passed: {hello: {world: true}}
Result: {hello: {there: true, world: true}}
I envisioned a recursive approach where the function would iterate over the passed object and if it encounters another object, call the function again with that object until all children are processed.
The challenge arises when dynamically comparing the children of both objects across various levels without prior knowledge of the depth or keys involved.
How can one programmatically access the properties of an object at unknown depths while writing code? Hardcoding or using methods like if (result[key1][key2][key3]...
may not be feasible, so what alternative approach can be taken?