Setting Object Properties Dynamically Using String Names in JavaScript
Given an object with a complex nested structure, it may be desirable to set a specific property deep within the object hierarchy. However, if the property name is only available as a string, conventional assignment techniques become inefficient.
To address this challenge, the assign() function demonstrates a recursive approach to traversing and setting object properties:
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; } var obj = {}, propName = "foo.bar.foobar"; assign(obj, propName, "Value");
This function allows you to dynamically set the property obj.foo.bar.foobar to a desired value, even when the property name is only available as a string.
The above is the detailed content of How to Dynamically Set Nested JavaScript Object Properties Using String Names?. For more information, please follow other related articles on the PHP Chinese website!