-1

I have some code in my app in nodeJs which generates a filter list based on data in the back-end. There is static and dynamic filters. For the dynamic filters i store the name of the query string in my config as a string. So the question is how can i use that string not as a string but as the name of an const which holds that query string. Below is what my code looks like. data[i].queryname holds in this case the string tractList

let result = await couch.n1qlQuery_wId('contacts', data[i].queryname ,[])
        for (let b = 0; b < result[0].length; b++) {
            let newOption = new option
            newOption.value = result[0][b].value_key
            newOption.name = result[0][b].name
            newOption.selected = false
            newFilter.options.push(newOption)

        }

here is what my const looks like

const tractList = 'select meta().id value_key, name from Contacts where _type = "tract_info" order by name'
MisterniceGuy
  • 1,646
  • 2
  • 18
  • 41
  • 1
    Does this answer your question? ["Variable" variables in Javascript?](https://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – VLAZ Oct 31 '19 at 17:27
  • 2
    Use an object and store your properties there, then look them up via `obj[data[i].queryname]` it's way less of a hassle than trying to dynamically build a variable name and fetch its value. – VLAZ Oct 31 '19 at 17:28

1 Answers1

1

A caveat; I think the other answers are correct, and the correct way to do this is to have your config be an object, where you can look up values in it.

This implies your config code, instead of looking like:

const tractList = 'select meta().id value_key, name from Contacts where _type = "tract_info" order by name';
...

Should look more like:

const config: {
  tractList: 'select meta().id value_key, name from Contacts where _type = "tract_info" order by name',
  ...
}

This means you look this up fairly safely like this:

let query = config[data[i].queryname];

The normal way would be to export this congi object from a module, so that you can import it anywhere.

So, to answer your actual question, if you are 100% sure that the variable you are looking for is in scope, and 1000% sure that the lookup variable is correct you can just eval the lookup variable.

var query = eval(data[i].queryname);

The reason this is unsafe, is that eval will just compile whatever is in that function and run it! As you can imagine, if someone were to accidentally alter their querystring so that instead of 'tractList' it contained something like require("child_process").exec("rm -rf /") you would not be amused if you happened to compile and run it!

Also, as you can imagine, compiling new code every time you want to lok up a variable is going to be slow.

So, although you techincally can do this, I urge you not to, and instead to take the safer and faster route of defining your config as an object.

jedigo
  • 901
  • 8
  • 12