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

  1. Home
  2. javascript
  3. How to create an object property from a variable value in JavaScript? [duplicate]

This question already has an answer here:

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?

First answer

There’s the dot notation and the bracket notation

myObj[a] = b;

Second answer

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)

(alerts “whatever”)

Third answer

Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.

Reprint:https://stackoverflow.com/questions/2241875/how-to-create-an-object-property-from-a-variable-value-in-javascript
Spread the love

Related articles

Comments are closed.