Home >Web Front-end >JS Tutorial >How Can I Dynamically Set Nested Property Values in JavaScript Objects Using a String Path?

How Can I Dynamically Set Nested Property Values in JavaScript Objects Using a String Path?

DDD
DDDOriginal
2024-12-09 16:55:11840browse

How Can I Dynamically Set Nested Property Values in JavaScript Objects Using a String Path?

Dynamic Property Setting in JavaScript Objects

Suppose we're given an object obj and a property name stored as a string propName, where propName can represent nested properties, such as "foo.bar.foobar."

Problem: How can we dynamically set the value of obj.foo.bar.foobar using propName as the path?

Solution: We can use the assign function below to set the property value dynamically:

function assign(obj, prop, value) {
    // Convert the string property name into an array of nested levels
    if (typeof prop === "string")
        prop = prop.split(".");

    // Check if the current level is the last (length == 1) or nested
    if (prop.length > 1) {
        // Shift the first level of nesting (e.g., "foo")
        var e = prop.shift();
        // Recursively call `assign` on the child object (e.g., obj.foo)
        assign(obj[e] =
                 Object.prototype.toString.call(obj[e]) === "[object Object]"
                 ? obj[e]
                 : {},
               prop,
               value);
    } else
        // For the last level, set the value directly
        obj[prop[0]] = value;
}

Usage:

// Object to modify
var obj = {};
// String representing the nested property path
var propName = "foo.bar.foobar";
// Value to set
var newValue = "hello world";

// Call the `assign` function to dynamically set the property value
assign(obj, propName, newValue);

// Check the updated value (for debugging purposes)
console.log(obj.foo.bar.foobar); // Output: "hello world"

The above is the detailed content of How Can I Dynamically Set Nested Property Values in JavaScript Objects Using a String Path?. 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