0

I'm working on a small javascript project. I'd like to receive a users console input and furthermore use the input to calculate some values.

I capture the users input in a variable called answer.

when using console.log(answer) the answer get printed.

let's say the user's answer was MILK

my current (working and hardcoded) call looks something like this:

let p = 0;
call.prices('MILKPRICE', (err, tic) => { p = tic.MILKPRICE; });

now I'd like to replace the word 'milk' with the user's answer

let p = 0;
call.prices(answer+'PRICE', (err, tic) => { p = tic.answer+'PRICE'; });

which returns undefined. is there a way to actually use the user's input and not hardcoding all possible records?

thank you very much

2
  • 2
    What is call.prices function? can you share the definition of this function? Commented Aug 18, 2021 at 13:06
  • unfortunately i don't have access to call.prices, however, it's mainly the issue that I cannot get p = tic.answer+'PRICE' this to actually use the user's input Commented Aug 18, 2021 at 13:11

1 Answer 1

3

If I identify your code correctly you are trying to use the dot notation to access a key in an object. That methode, thought nicer to read and write does not support variables, however you can simply use brackets for accessing the field.

Like so:

const prices = {
  MILKPRICE: 2,
  WATERPRICE: 1
}
const answer = "MILK"

// this will fail
console.log(prices.answer+"PRICE");

// this will work
console.log(prices[answer+"PRICE"]);

Sign up to request clarification or add additional context in comments.

1 Comment

thank you! that did the job just perfectly fine. call.prices(answer+'PRICE', (err, tic) => { p = tic[answer+'PRICE']; });

Your Answer

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.