Home  >  Article  >  Web Front-end  >  How to Dynamically Set Properties in Nested JavaScript Objects?

How to Dynamically Set Properties in Nested JavaScript Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 08:16:29291browse

How to Dynamically Set Properties in Nested JavaScript Objects?

Dynamic Property Assignment in Nested 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.

Function Implementation

<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>

Example Usage

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>

Result

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn