Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object property from a variable value in JavaScript? [duplicate]

I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:

var myObj = new Object; var a = 'string1'; var b = 'string2'; myObj.a = b;  alert(myObj.string1); //Returns 'undefined' alert(myObj.a); //Returns 'string2' 

In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?

like image 415
ecu Avatar asked Feb 11 '10 02:02

ecu


People also ask

How do you copy properties from one object to another in JavaScript?

assign() The Object. assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Does object values create a copy?

One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, booleans, etc – are always copied “as a whole value”.


2 Answers

There's the dot notation and the bracket notation

myObj[a] = b; 
like image 107
philfreo Avatar answered Sep 23 '22 01:09

philfreo


ES6 introduces computed property names, which allow you to do

var myObj = {[a]: b}; 

Note browser support is currently negligible.

like image 43
Oriol Avatar answered Sep 23 '22 01:09

Oriol