Home > Web Front-end > JS Tutorial > How to Assign Values to Deeply Nested JavaScript Objects Using String Property Names?

How to Assign Values to Deeply Nested JavaScript Objects Using String Property Names?

DDD
Release: 2024-12-15 20:04:17
Original
789 people have browsed it

How to Assign Values to Deeply Nested JavaScript Objects Using String Property Names?

Dynamic Property Assignment in JavaScript Using String Names

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

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

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");
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template