0

I'm trying to send this data to an API:

data={
 "to":{name : "to whom"}
};

But JavaScript doesn't allow me to do so (note that "name" is a variable). On the other hand it allows me to do as following:

data={
  "to" :{"me": "to whom"}
};

What am I doing wrong ?

Heretic Monkey
  • 11,078
  • 7
  • 55
  • 112
Leonardo Menezes
  • 496
  • 5
  • 11

2 Answers2

0

ES5 doesn't natively allow you to do this. you'd need to create the inner hash as a variable and use that.

var address = {};
address[name] = 'to whom';

var data = {
  to: address
};

If you're using ES6 syntax, you can add brackets in the declaration

var data = {
  to: { [name]: 'to whom' }
};
PhilVarg
  • 4,613
  • 2
  • 18
  • 34
0

In JavaScript {name : "to whom"} and {"name" : "to whom"} is exactly the same. What you are looking for are computed property names:

var data = {
    "to": {[name]: "to whom"}
};

This syntax is supported in node v6.0.

Tamas Hegedus
  • 26,761
  • 10
  • 55
  • 91