Home >Web Front-end >JS Tutorial >How Can I Dynamically Set Nested Property Values in JavaScript Objects Using a String Path?
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!