In JavaScript, scenarios arise where you may need to set a deeply nested property of an object using only its string representation. For example:
var obj = {}; var propName = "foo.bar.foobar";
To set the property obj.foo.bar.foobar to "hello world", you can utilize the following function:
function assign(obj, prop, value) { if (typeof prop === "string") prop = prop.split("."); if (prop.length > 1) { var e = prop.shift(); assign(obj[e] = Object.prototype.toString.call(obj[e]) === "[object Object]" ? obj[e] : {}, prop, value); } else obj[prop[0]] = value; }
This function iterates through the nested property structure, creating any missing objects along the way. It assigns the final value to the desired property at the end.
Usage:
assign(obj, propName, "hello world");
After executing this assignment, obj.foo.bar.foobar will be set to "hello world".
The above is the detailed content of How to Assign Values to Deeply Nested JavaScript Objects Using String Property Names?. For more information, please follow other related articles on the PHP Chinese website!