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

How Can You Dynamically Set Properties on Nested Objects in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 15:00:461017browse

How Can You Dynamically Set Properties on Nested Objects in JavaScript?

Dynamic Property Setting for Nested Objects

Setting properties dynamically on complex, nested objects can be a challenge. To address this, consider the following function:

<code class="javascript">function set(path, value) {
    var schema = obj;  // 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>

With this function, you can set or overwrite properties on deeply nested objects using a dot-separated path:

<code class="javascript">set('db.mongodb.user', 'root');</code>

When the function encounters a nonexistent object along the path, it creates an empty object at that level. This ensures that the property can be set at the correct level without merging or overwriting existing values.

For example, given the object:

<code class="javascript">var obj = {
    db: {
        mongodb: {
            host: 'localhost'
        }
    }
};</code>

Setting db.mongodb.user to 'root' would result in:

<code class="javascript">obj = {
    db: {
        mongodb: {
            host: 'localhost',
            user: 'root'
        }
    }
};</code>

By dynamically setting properties, you can manipulate complex nested objects with ease, even when the object structure is unknown or varies. This technique provides a powerful and flexible way to access and modify data within complex data structures.

The above is the detailed content of How Can You Dynamically Set Properties on Nested Objects in JavaScript?. 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