Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 814
Todd R Avatar asked Mar 29 '09 18:03

Todd R


People also ask

How do you add a property to an object in JavaScript?

To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.

How do you add a property value to an object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

Can I add a variable to an object in JavaScript?

The name: values pairs in JavaScript objects are called properties. We can add the property to JavaScript object using a variable as the name by using dot notation or bracket notation.

How properties are assigned to an object in JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.


2 Answers

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

like image 140
Christian C. Salvadó Avatar answered Oct 05 '22 03:10

Christian C. Salvadó


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 } 
like image 29
kube Avatar answered Oct 05 '22 05:10

kube