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

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

Linda Hamilton
Release: 2024-11-04 15:00:46
Original
1049 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template