"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Dynamically Add Properties to JavaScript Objects Using Variables?

How Can I Dynamically Add Properties to JavaScript Objects Using Variables?

Posted on 2025-03-24
Browse:263

How Can I Dynamically Add Properties to JavaScript Objects Using Variables?

Dynamically Creating Object Properties through Variables

When seeking to add new properties to an object in JavaScript, relying solely on the dot notation can prove limiting. Consider the need to assign a property name stored in a variable. In such situations, the answer lies in employing the bracket notation.

Imagine an object, aptly named myObj, that lacks the desired property string1. Utilizing the dot notation, you may attempt:

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

Upon inspecting myObj, you'll notice the 'string1' property remains elusive, replaced by 'a'. This is where bracket notation shines:

myObj[a] = b;

This modification grants myObj the 'string1' property with the 'string2' value. The key to this success lies in treating the property name as a string within brackets, allowing for dynamic property creation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3