Reputation: 139
Js newbie here. I have two variables, the value of which I'm extracting from user input (which is a string).
Now I have a dictionary :
let dict = {
'p': "100 units" ,
'q': "200 units",
'g': "500 units",
'e': "10 units"
}
What I want to do here is to write a condition that allows users to enter only the key values in the dict (for example, "p for 100 units"), that is, sends a fallback response "This option is not available"(console.log) If I do this using a loop on Object.keys(dict), the response gets sent 4 times (equal to the number of key-value pairs in the dictionary).
How do I check that what the user has entered corresponds to my dictionary and send a response only once if he hasn't? I reckon I would have to loop over the dictionary in any case.
I also want to place a return for the if block. i.e:
if(whatever){
//code
return 0
}
else return 1
Any other ideas/approaches I can try?
Upvotes: 0
Views: 96
Reputation: 18619
You can use the in
operator to check if a key is present in an object, like:
if(input in dict){}
Using it, you can simply create a such program, where dict
is your object and input
is the key the user pressed:
console.log(input in dict ? 'Chosen' + dict[input] : 'Fallback text')
Upvotes: 2
Reputation: 2804
Here's some code you might find useful:
letter="e";
console.log((units=dict[letter])?letter+" for "+units:"This option is not available");
letter
is the user's input. You could/should check for no input|more than one letter.
dict[letter]
returns value for key letter
. If not found, it returns undefined which is like false.
We assign that value to a variable units
so we don't have to look it up again (useful in very complicated objects and functions to save resources).
The condition?ifTrue:ifFalse
is evaluated (I've put the condition in parentheses - to avoid having to think what might be evaluated without them. Probably the same. Usually, I used this format: ((condition)?(do/value if true):(do/value if false))
.
The rest should be obvious.
I would recommend consistent indentation and spacing:
let dict = {
'p': "100 units",
'q': "200 units",
'g': "500 units",
'e': "10 units"
};
const keys = Object.keys(dict);
console.log(keys) // output ['p', 'q', 'g', 'e']
Upvotes: 1
Reputation: 188
Object.keys returns an array of keys like so:
let dict = {
'p': "100 units" ,
'q': "200 units",
'g': "500 units",
'e': "10 units"}
const keys = Object.keys(dict)
console.log(keys) // output ['p', 'q', 'g', 'e']
Therefore if you want to check the letter a user enters you need to loop through the array of keys and use if statement inside the loop to check the user input:
let userInput = 'g'
for(key of keys){
if(key === userInput){
console.log(dict[key]) //output 500 units
}else{
console.log('Fall back response')
}
}
Read the documentation here for details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
Upvotes: 2