Home > Web Front-end > JS Tutorial > How to Dynamically Add Properties to JavaScript Objects Using Variable Names?

How to Dynamically Add Properties to JavaScript Objects Using Variable Names?

Susan Sarandon
Release: 2024-12-23 19:59:13
Original
724 people have browsed it

How to Dynamically Add Properties to JavaScript Objects Using Variable Names?

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

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

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' }
Copy after login

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' }
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template