Home >Web Front-end >JS Tutorial >How to Dynamically Assign Object Properties in JavaScript Using Variable Names?

How to Dynamically Assign Object Properties in JavaScript Using Variable Names?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 04:28:17954browse

How to Dynamically Assign Object Properties in JavaScript Using Variable Names?

How to Assign Object Properties Dynamically Using Variable Names in JavaScript

When working with objects in JavaScript, it can be useful to create properties dynamically based on the values of variables. One common scenario is when you have a variable containing the name of a desired property and another variable containing the value for that property.

However, using dot notation to assign a value to an object property whose name is stored in a variable often results in an undefined value, as seen in the following example:

var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;

alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'

To create a property dynamically with the name stored in a variable, you can use bracket notation instead of dot notation:

myObj[a] = b;

In this notation, the property name is enclosed in square brackets, allowing you to assign the value of b to the property string1.

The above is the detailed content of How to Dynamically Assign Object Properties in JavaScript Using Variable 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