I would like to get values (result) from dictionnaries with variable1( the name of the dictionnary that the user enter.) Please do anyone know? I would help a lot because I have more than 300 dictionnaries. Cheers
app.get('/', function (req, res) {
variable1=req.query['variable1']
var dictionnary1 = {one:0.2187, two:0.1148};
var dictionnary2 = {one:0.3257, two:0.1234};
function calculate(){
result=variable1.one
}
calculate()
-
I would like that If the user enter "dictionnary1" the function calculate will return 0.2187Ben– Ben2017年11月07日 07:28:06 +00:00Commented Nov 7, 2017 at 7:28
-
may you try to explain what exactly you mean? do you want to know how to get a parameter from the request? do you want to know how to dynamically add entries to a dictionary (fields in an Object)?FrontTheMachine– FrontTheMachine2017年11月07日 07:28:32 +00:00Commented Nov 7, 2017 at 7:28
-
Use an array of dictionaries and access them by index.Bergi– Bergi2017年11月07日 07:38:52 +00:00Commented Nov 7, 2017 at 7:38
1 Answer 1
(Side note: "dictionary" has only one 'n' in it. I'm guessing you've translated your code from another language into English. I went back and forth, but I think it's probably best that I use your spelling in the code portions of this answer.)
Put the dictionaries in an object or Map with the dictionary name as the key (do this once, outside the get callback):
// Object
var dictionnaries = {
dictionnary1: {one:0.2187, two:0.1148},
dictionnary2: {one:0.3257, two:0.1234}
};
// Map
var dictionaries = new Map([
["dictionnary1", {one:0.2187, two:0.1148}],
["dictionnary2", {one:0.3257, two:0.1234}]
]);
...then in the get callback, use variable1 to look up the dictionary:
// Using an object
var dictionnary = dictionnaries[variable1];
// Using a Map
var dictionnary = dictionnaries.get(variable1);
...and pass that to calculate as an argument:
var result = calculate(dictionnary);
...where calculate looks like (I assume it's more complex than this):
function calculate(dictionnary) {
return dictionnary.one;
}
E.g., something like:
var dictionnaries = {
dictionnary1: {one:0.2187, two:0.1148},
dictionnary2: {one:0.3257, two:0.1234}
};
function calculate(dictionnary) {
return dictionnary.one;
}
app.get('/', function (req, res) {
var variable1 = req.query['variable1'];
var dictionnary = dictionnaries[variable1];
var result = calculate(dictionnary);
// Use `result` in the response...
});