Home >Web Front-end >JS Tutorial >How Can I Set Nested JavaScript Object Properties Using String Names?

How Can I Set Nested JavaScript Object Properties Using String Names?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-24 11:02:14374browse

How Can I Set Nested JavaScript Object Properties Using String Names?

Setting Nested Object Properties Using String Names in JavaScript

In JavaScript, accessing and modifying object properties is essential for managing your data. However, what if you're only provided with the property name as a string instead of its direct key sequence? This can arise in scenarios where properties are dynamically generated or received as user input.

Consider the following object:

var obj = {};

And a property name:

var propName = "foo.bar.foobar";

To set the value of obj.foo.bar.foobar, traditionally you would use the following syntax:

obj.foo.bar.foobar = "hello world";

However, this approach requires manually traversing each property in the chain, which can become tedious and error-prone, especially for deeply nested properties.

Recursive Property Assignment Function

To address this challenge, a recursive function called assign can be implemented to simplify the assignment process:

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 takes an object (obj), a property name (prop) as a string, and a value (value) to assign to the property. It recursively traverses the object hierarchy and sets the appropriate property to the specified value.

Usage

To set the value of obj.foo.bar.foobar using the assign function:

var obj = {},
    propName = "foo.bar.foobar";

assign(obj, propName, "Value");

This code will create the necessary nested properties and set the value of obj.foo.bar.foobar to "Value".

By utilizing recursive property assignment functions, you can dynamically access and modify nested object properties in JavaScript using string names, providing a flexible and scalable solution for complex data structures.

The above is the detailed content of How Can I Set Nested JavaScript Object Properties Using String Names?. 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