Home > Article > Web Front-end > How to Dynamically Set Properties in Nested JavaScript Objects?
Setting nested object properties can be a programmatically complex task, especially when the property path and value can vary in depth and type. To simplify this process, we can create a function that dynamically traverses and sets properties within an object.
<code class="javascript">function set(path, value) { var schema = obj; // Moving reference to internal objects within obj var pList = path.split('.'); var len = pList.length; for (var i = 0; i < len - 1; i++) { var elem = pList[i]; if (!schema[elem]) schema[elem] = {}; schema = schema[elem]; } schema[pList[len - 1]] = value; }</code>
Consider the following nested object:
<code class="javascript">var obj = { db: { mongodb: { host: 'localhost' } } };</code>
To set a property at a specific path, we can use the set() function:
<code class="javascript">set('db.mongodb.user', 'root');</code>
Applying the set() function to the example object would produce:
<code class="javascript">obj = { db: { mongodb: { host: 'localhost', user: 'root' } } };</code>
The above is the detailed content of How to Dynamically Set Properties in Nested JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!