441

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ecu
  • 4,433
  • 2
  • 16
  • 4
  • 2
    @daniella The object property is absolutely plain javascript. That it is used in a jQuery example is irrelevant. – Bergi Mar 17 '17 at 23:15
  • 1
    For the record, never use `new Object`; Use an object literal instead: `var myObj = {}` – fregante Jun 22 '19 at 06:17

9 Answers9

564

There's the dot notation and the bracket notation

myObj[a] = b;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
philfreo
  • 41,941
  • 26
  • 128
  • 141
  • 14
    They're not really "equivalent"; `myObj.a = b` means something different to `myObj[a] = b` (unless `a == 'a'`) but whatever... this is what you want. – Dominic Cooney Feb 11 '10 at 02:44
  • 16
    What I meant is that they're equivalent ways to set a property. Obviously they behave differently (hence the purpose of posting this answer) - but they have the same result. – philfreo Feb 11 '10 at 02:46
  • 5
    philfreo: except that they _don't_ have the same result, which is the basis for this question. – bukzor Aug 24 '11 at 22:00
  • 24
    I was just saying there are two ways to set an object, one for when the key is hard coded and one when it's variable. I meant the outcome of the object is equivalent regardless if you use `myObj['foo'] = 'bar'` or `myObj.foo = 'bar'` – philfreo Aug 25 '11 at 03:46
  • 2
    Somehow this method gave me an array `[a:b]` instead of `{a:b}` – Jhourlad Estrella Aug 28 '18 at 02:49
547

ES6 introduces computed property names, which allow you to do

var myObj = {[a]: b};
Chrisuu
  • 272
  • 3
  • 13
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 16
    Works with Babel though. – Zequez Nov 06 '15 at 02:58
  • 25
    For ones like myself who develop using Node.js and need this for backend only, thus not worried about browser implementations, this was VERY useful. Should have more upvotes! – lucasnadalutti Nov 06 '15 at 03:00
  • 2
    This actually looks like the only way to create an anonymous object with a variable as the key, very useful when you just need to push this onto an array. – cocheci Nov 06 '15 at 12:26
  • 3
    Which browsers does this currently support? – Jessica May 11 '16 at 19:08
  • 10
    @Jessica https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_computed_properties – Oriol May 11 '16 at 19:33
  • 1
    Great! More browsers support it? – stefcud May 17 '16 at 17:29
  • 1
    For a reference see [MDN ES2015 Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) Browser compatibility: `Chrome 47+`, `Edge`, `Opera 34+` and `Safari 8+`. Not supported in `IE <= 11`. – Will B. Jul 03 '19 at 19:43
  • 1
    This pretty much supports a lot of browsers now. Except IE ofcourse. – Arpan Srivastava Aug 21 '19 at 13:02
  • 1
    Browser Support by now is widespread, works like charm – Julio Spinelli Mar 12 '22 at 16:40
87

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

// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);

(alerts "whatever")

King-Wizard
  • 15,628
  • 6
  • 82
  • 76
cgp
  • 41,026
  • 12
  • 101
  • 131
11

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.

user286806
  • 495
  • 1
  • 5
  • 14
8

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 shorter?

Tal Joffe
  • 5,347
  • 4
  • 25
  • 31
user2846569
  • 2,752
  • 2
  • 23
  • 24
5

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.

Aaron George
  • 128
  • 1
  • 6
5

You cannot use a variable to access a property via dot notation, instead use the array notation.

var obj= {
     'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
jroi_web
  • 1,992
  • 22
  • 23
4

As $scope is an object, you can try with JavaScript by:

$scope['something'] = 'hey'

It is equal to:

$scope.something = 'hey'

I created a fiddle to test.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tuan
  • 893
  • 1
  • 9
  • 24
0

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

Community
  • 1
  • 1
Trent
  • 335
  • 2
  • 8