I want to add to Object with variables, like this
a = 'name'
object = {'age': 12, 'weight': 120}
I want this to
{'name': 'bob'}
I do this
object = {a: 'bob'}
but it give me
{'a': 'bob'}
how can I fixed it? I must use variables
I want to add to Object with variables, like this
a = 'name'
object = {'age': 12, 'weight': 120}
I want this to
{'name': 'bob'}
I do this
object = {a: 'bob'}
but it give me
{'a': 'bob'}
how can I fixed it? I must use variables
Just assign it with the bracket notation after deleting the former content.
var a = 'name',
object = { 'age': 12, 'weight': 120 };
object = {}; // delete all properties
object[a]= 'Bob'; // assign new property
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can't do this in one line. But you can do like this :
object = {};
object [a] = 'bob';
In ECMAScript 2015 there are computed property names:
var a = 'name';
var obj = {[a]:'fred'};
However there may not be sufficient support yet. See the MDN browser compatability table.