0

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) });
Anish
  • 1
  • 2

1 Answers1

0

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

Jerson
  • 1,700
  • 2
  • 10
  • 14