Add properties to JavaScript objects using variables as keys?
P粉071559609
2023-08-24 18:04:17
<p>I'm using jQuery to extract an item from the DOM and want to set the object's properties using the DOM element's <code>id</code>. </p>
<h3>Example</h3>
<pre class="brush:js;toolbar:false;">const obj = {}
jQuery(itemsFromDom).each(function() {
const element = jQuery(this)
const name = element.attr('id')
const value = element.attr('value')
//Here is the problem
obj.name = value
})
</pre>
<p>If <code>itemsFromDom</code> contains an element with <code>id</code> being "myId", I want <code>obj</code> to have an element named "myId" "properties. The above code gives me <code>name</code>. </p>
<p>How to name properties of an object using variables using JavaScript? </p>
With ECMAScript 2015, you can use square bracket notation directly in the object declaration:
Where
key
can be any type of expression (such as a variable), returning a value:You can use the equivalent syntax:
Example:
Or use ES6 features:
In both examples,
console.log(obj)
will return:{ the_key: 'the_value' }