Dynamic Property Assignment for Nested Objects
In the realm of JavaScript, objects can be intricate structures with varying levels of depth and properties. Often, we encounter scenarios where we need to dynamically assign or overwrite properties within deeply nested objects. This can prove challenging, especially when the property path and value can be arbitrary.
The challenge:
Given an object with an arbitrary number of levels and properties, we seek to find a function that enables us to set (or overwrite) properties dynamically using a string representation of the property path, as shown below:
<code class="javascript">var obj = { db: { mongodb: { host: 'localhost', }, }, }; // Set a new property set('db.mongodb.user', 'root');</code>
The solution:
To address this challenge, we introduce a function named set that dynamically modifies properties within nested objects. Below is the implementation:
<code class="javascript">function set(path, value) { var schema = obj; // Moving reference to internal objects within 'obj' var pList = path.split('.'); // Split the property path into an array of elements var len = pList.length; for (var i = 0; i < len - 1; i++) { var elem = pList[i]; if (!schema[elem]) schema[elem] = {}; // If the element doesn't exist, create an empty object schema = schema[elem]; // Advance the schema reference to the next level } schema[pList[len - 1]] = value; // Update or create the property at the leaf level }</code>
Usage:
To set a property, simply pass the property path and corresponding value to the set function as seen in the example below:
<code class="javascript">set('db.mongodb.user', 'root');</code>
Output:
The resulting object after setting the property dynamically:
<code class="javascript">{ db: { mongodb: { host: 'localhost', user: 'root', }, }, }</code>
Through this function, we gain the flexibility to modify nested properties dynamically, enabling efficient and versatile object manipulation.
The above is the detailed content of How Can You Dynamically Assign Properties to Nested Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!