0

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()

asked Nov 7, 2017 at 7:26
3
  • I would like that If the user enter "dictionnary1" the function calculate will return 0.2187 Commented 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)? Commented Nov 7, 2017 at 7:28
  • Use an array of dictionaries and access them by index. Commented Nov 7, 2017 at 7:38

1 Answer 1

2

(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...
});
answered Nov 7, 2017 at 7:29
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.