Categories
javascript jquery object syntax

Add a property to a JavaScript object using a variable as the name?

320

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?

2

531

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

1

  • 1

    Is there a name for this syntax? Or a link I can read more on?

    Feb 9 at 19:52

149

With ECMAScript 2015 you can do it directly in object declaration using bracket notation:

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value:

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

8

  • 14

    This question is about modifying existing object, not creating a new one.

    Dec 26, 2015 at 10:16

  • 33

    This particular question might be about modifying but it’s referenced by other questions that are about dynamically creating objects and so I ended up here and happily benefited from this answer.

    Oct 29, 2016 at 17:40

  • 2

    @wOxxOm lol yeah why would I go through the hassle of obj[name]=value when I could just use your suggestion instead

    – chiliNUT

    Mar 17, 2017 at 23:17

  • 2

    I’m not sure what ECMAScript 6 is, but I appreciate it very much

    Apr 10, 2017 at 12:23

  • 2

    @ArthurTarasov: ECMAScript 6 is more formally called ECMAScript 2015 (“ES2015”) aka ECMAScript 6th edition (“ES6”). It’s the specification for JavaScript released June 2015. Since then we’ve had ES2016 and soon we’ll have ES2017, they’re on a yearly cycle now.

    Apr 18, 2017 at 16:06

12

You can even make List of objects like this

var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
    var feeType = {};

    var $ID = $(this).find("input[id^=txtFeeType]").attr('id');

    feeType["feeTypeID"] = $('#ddlTerm').val();
    feeType["feeTypeName"] = $('#ddlProgram').val();
    feeType["feeTypeDescription"] = $('#ddlBatch').val();

    feeTypeList.push(feeType);
});