How to Dynamically Add Properties to a JavaScript Object
When working with DOM elements, it's common to need to set properties on objects using the IDs of those elements. Consider the following situation:
You have an array of DOM elements retrieved using jQuery, and you want to set properties on an object using the IDs of each element.
const obj = {}; jQuery(itemsFromDom).each(function() { const element = jQuery(this); const name = element.attr('id'); const value = element.attr('value'); // This line does not work as intended: obj.name = value; });
The above code will set a property on the object, but the property name will always be "name" regardless of the ID of the element. To dynamically set the property name using a variable, you should use brackets and the variable name:
obj[name] = value;
This allows you to create properties on the object using the IDs or any other variable as the property name.
let obj = {}; obj["the_key"] = "the_value"; console.log(obj); // Output: { the_key: 'the_value' }
Alternatively, you can use ES6 features for more concise syntax:
let key = "the_key"; let obj = { [key]: "the_value" }; console.log(obj); // Output: { the_key: 'the_value' }
Using brackets allows you to dynamically set property names on JavaScript objects, giving you greater flexibility and control over data manipulation.
The above is the detailed content of How to Dynamically Add Properties to JavaScript Objects Using Variable Names?. For more information, please follow other related articles on the PHP Chinese website!