Add properties to JavaScript objects using variables as keys?
P粉071559609
P粉071559609 2023-08-24 18:04:17
0
2
533
<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>
P粉071559609
P粉071559609

reply all(2)
P粉116654495

With ECMAScript 2015, you can use square bracket notation directly in the object declaration:

var obj = {
  [key]: value
}

Where key can be any type of expression (such as a variable), returning a value:

var obj = {
  ['hello']: 'World',
  [x + 2]: 42,
  [someObject.getId()]: someVar
}
P粉696605833

You can use the equivalent syntax:

obj[name] = value

Example:

let obj = {};
obj["the_key"] = "the_value";

Or use ES6 features:

let key = "the_key";
let obj = {
  [key]: "the_value",
};

In both examples, console.log(obj) will return: { the_key: 'the_value' }

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template