-1

given this example:

var obj = {
    'a': 1,
    'b': 2
};

will be a:1, b:2 as excected. But what if I have:

var b = 'myProperty';
var obj = {
    'a': 1,
    b: 2
};

I wanted to have a: 1, myProperty: 2 but I still got a: 1, b: 2! How to fix it?

vol7ron
  • 40,809
  • 21
  • 119
  • 172
John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 1
    Check the answers here: https://stackoverflow.com/questions/2241875/how-to-create-an-object-property-from-a-variable-value-in-javascript – Mohamed Ibrahim Elsayed Mar 03 '18 at 20:05
  • 2
    Please use the search: [`[javascript] object literal variable`](https://stackoverflow.com/search?q=%5Bjavascript%5D+object+literal+variable) – Felix Kling Mar 03 '18 at 20:05
  • 1
    Possible duplicate: https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object – kingdaro Mar 03 '18 at 20:06

2 Answers2

1

Variables in object property names are only allowed using the bracket notation:

var b = 'myProperty';

var obj = {
    'a': 1
};

obj[b] = 2;

console.log(obj.myProperty); // logs 2
Mezo Istvan
  • 2,664
  • 1
  • 14
  • 17
1

Hope this helps!

var b = 'myProperty';
var obj = {
    'a': 1
};
obj[b]=2;
console.log(obj)
yajiv
  • 2,901
  • 2
  • 15
  • 25