search

Home  >  Q&A  >  body text

Add properties to JavaScript objects using variables as keys?

<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粉071559609P粉071559609553 days ago577

reply all(2)I'll reply

  • P粉116654495

    P粉1166544952023-08-25 16:58:11

    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
    }

    reply
    0
  • P粉696605833

    P粉6966058332023-08-25 10:28:30

    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' }

    reply
    0
  • Cancelreply