简体   繁体   中英

How do I get get the value of a variable?

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"}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM