0

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

nataila
  • 1,549
  • 4
  • 18
  • 25

3 Answers3

2

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • this will give me `{'name': 'bob', 'age': 12, 'weight': 120}` I just want `{'age': 12, 'weight': 120}` to `{'name': 'bob'}` – nataila Sep 30 '15 at 12:00
0

You can't do this in one line. But you can do like this :

object = {};
object [a] = 'bob';
Magus
  • 14,796
  • 3
  • 36
  • 51
0

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.

RobG
  • 142,382
  • 31
  • 172
  • 209