Home > Web Front-end > JS Tutorial > body text

How to Dynamically Set Properties in Nested JavaScript Objects?

Linda Hamilton
Release: 2024-10-31 08:16:29
Original
294 people have browsed it

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

Example Usage

Consider the following nested object:

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

To set a property at a specific path, we can use the set() function:

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

Result

Applying the set() function to the example object would produce:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!