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

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


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


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}


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