Javascript – Add a property to a JavaScript object using a variable as the name

javascriptjqueryobjectsyntax

I'm pulling items out of the DOM with jQuery and want to set a property on an object using the id of the DOM element.

Example

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

If itemsFromDom includes an element with an id of "myId", I want obj to have a property named "myId". The above gives me name.

How do I name a property of an object using a variable using JavaScript?

Best Answer

You can use this equivalent syntax:

obj[name] = value

Example:

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

or with ES6 features:

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

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