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

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?

This question is related to javascript jquery object syntax

The answer is


With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:

var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));

If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.

Object.keys(myObject)
.map(el =>{
 const obj = {};
 obj[el]=myObject[el].code;
 console.log(obj);
});

const data = [{
    name: 'BMW',
    value: '25641'
  }, {
    name: 'Apple',
    value: '45876'
  },
  {
    name: 'Benz',
    value: '65784'
  },
  {
    name: 'Toyota',
    value: '254'
  }
]

const obj = {
  carsList: [{
    name: 'Ford',
    value: '47563'
  }, {
    name: 'Toyota',
    value: '254'
  }],
  pastriesList: [],
  fruitsList: [{
    name: 'Apple',
    value: '45876'
  }, {
    name: 'Pineapple',
    value: '84523'
  }]
}

let keys = Object.keys(obj);

result = {};

for(key of keys){
    let a =  [...data,...obj[key]];
    result[key] = a;

}

First we need to define key as variable and then we need to assign as key as object., for example

_x000D_
_x000D_
var data = {key:'dynamic_key',value:'dynamic_value'}_x000D_
var key = data.key;_x000D_
var obj = { [key]: data.value}_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_


ajavascript have two type of annotation for fetching javascript Object properties:

Obj = {};

1) (.) annotation eg. Obj.id this will only work if the object already have a property with name 'id'

2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.

so for below example:

A new property will be created always when you write Obj[name]. And if the property already exist with the same name it will override it.

const obj = {}
    jQuery(itemsFromDom).each(function() {
      const element = jQuery(this)
      const name = element.attr('id')
      const value = element.attr('value')
      // This will work
      obj[name]= value;
    })

objectname.newProperty = value;


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

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
}

There are two different notations to access object properties

  • Dot notation: myObj.prop1
  • Bracket notation: myObj["prop1"]

Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.

Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.

So, these all set the myObj property named prop1 to the value Hello:

// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";

// brackets+literal
myObj["prop1"] = "Hello";

// using a variable
var x = "prop1"; 
myObj[x] = "Hello";                     

// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";     

Pitfalls:

myObj.[xxxx] = "Hello";      // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello";      // wrong: this expects a variable called prop1

tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.

Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.


With lodash, you can create new object like this _.set:

obj = _.set({}, key, val);

Or you can set to existing object like this:

var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }

You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:

_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }

If you want to add fields to an object dynamically, simplest way to do it is as follows:

 var params= [
{key: "k1", value=1},
{key: "k2", value=2},
{key: "k3", value=3}];

for(i=0; i< params.len; i++) {
  data[params[i].key] = params[i].value
}

This will create data object which has following fields:

{k1:1, k2:2, k3:3}

Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:

this.setState({ [`${name}`]: value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[name]));
    });

PS: Please mind the quote character.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?