简体   繁体   中英

$$key php equivalent in node.js

I have an array and I am using foreach loop to iterate through that array and I want each key in that array to be converted in to a varible. like we do in PHP. for example:

foreach (['browser_id', 'device_id', 'os_id', 'event', ] as $var) {
            $$var = $request->$var ?? Session::put($var) ?? "";
        }

How to do exactly this in Node.js? I have this array

var paramss = ['browser_id', 'device_id', 'os_id', 'event', 'eventName', 'billingstatus', 'step'];

I want to loop these using foreach and convert each of these keys in to a varible. like browser_id,device_id etc will be a varible.Please help

I have tried this:

paramss.forEach(element => {
  var element = req.query[element] ? req.query[element] : '';
console.log(element) });

window object is not available in NodeJS however you can use global

global["foo"] = 'bar'

So you can access it using foo variable

console.log(foo) // bar

so in your case you can do this

paramss.forEach(element => {
  global[element] = req.query[element] ? req.query[element] : '';
})

then you can get the element as variable defined

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