1

This is my a snippet code from my nodeJs progam here. I have a map called transMap. I would like to read the value for yy, get "ipaddress" and pass it out as json along with its value. I would have expected json response to be { "ipaddress" : "http://derivedURL.com"}. But what I get is { arg : "http://derivedURL.com"}

I am missing something really basic here.

var transMap = new Map();
        transMap.set('xx', {rPath:'/xxs', sn:2,res:['rid']});
        transMap.set('yy', {rPath:'/yys', sn:3, res: ['ipaddress','dns']});
        transMap.set('zz', {rPath:'/zzs', sn:4, res:['uri', 'fqdn']});

       var arg = (transMap.get(yy)).res[0] ; //arg = ipaddress
       var jsonResponse = { arg : "http://derivedURL.com"}; 
       console.log(jsonResponse); //

Edit1: arg has to get the value of "ipaddress" obtained from transMap. Derived URL is derived from a different function thats immaterial to this discussion.

My console now reads: { arg : "http://derivedURL.com"}. But I want it to read { "ipaddress" : "http://derivedURL.com"}

lonelymo
  • 3,972
  • 6
  • 28
  • 36
  • possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](http://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – Jonathan Lonowski Mar 02 '14 at 07:46

1 Answers1

2

When you do :

var jsonResponse = {
  arg : 'someArg'
}

arg does not get evaluated to it's value. Instead it gets used as 'arg' itself. To have it evaluated to it's value, you can set it like this:

jsonResponse[arg] = 'someArg'

When you use the [] notation, the key (here: arg) always gets evaluated in scope.

Example jsFiddle

Myrne Stol
  • 11,222
  • 4
  • 40
  • 48
Ayush
  • 41,754
  • 51
  • 164
  • 239
  • This answer doesnt help me or I am not understanding it. Please see my edit to the question Edit1: arg has to get the value of "ipaddress". Derived URL is derived from a different function thats immaterial to this discussion. My console now reads: { arg : "http://derivedURL.com"}. But I want it to read { "ipaddress" : "http://derivedURL.com"} – lonelymo Mar 02 '14 at 10:12
  • Instead of `var jsonResponse = { arg : "http://derivedURL.com"};`, do `var jsonResponse[arg] = "http://derivedURL.com";`. – Ayush Mar 03 '14 at 18:29