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

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

This question already has an answer here:

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

10 answers

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?

Solutions/Answers:

Solution 1:

There’s the dot notation and the bracket notation

myObj[a] = b;

Solution 2:

ES6 introduces computed property names, which allow you to do

var myObj = {[a]: b};

Note browser support is currently negligible.

Solution 3:

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”)

Solution 4:

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.

Solution 5:

Oneliner:

obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);

Or:

attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);

Anything more shorter?

Solution 6:

You could just use this:

function createObject(propName, propValue){
    this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');

Anything you pass as the first parameter will be the property name, and the second parameter is the property value.