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

How to Dynamically Set Nested JavaScript Object Properties Using String Names?

DDD
Release: 2024-12-05 03:00:11
Original
852 people have browsed it

How to Dynamically Set Nested JavaScript Object Properties Using String Names?

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

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!

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