0

Javascript function that takes a single argument. Use that argument value which is a string to return the appropriate value from the matched object key.

 function someFunction(someArg) {

var message = {
    bob: "Hello bob",
    mike: "Hello mike",
    tara: "Hello tara"
}

console.log(message +  " " + message.someArg + " " + someArg + " " + message.bob);

}

what is returned is

 [object Object] undefined bob Hello bob

Where undefined is returned in the console log, JavaScript should return the message "Hello bob" as the value of someArg is "bob", calling message.bob returns the correct result.

1
  • return message[someArg]; Commented Mar 20, 2018 at 13:02

3 Answers 3

2

To print it properly, you'll have to:

  • Stringify the message object
  • Refer to the property of message in a correct manner

Try this

function someFunction(someArg) {
   var message = {
    bob: "Hello bob",
    mike: "Hello mike",
    tara: "Hello tara"
   }
   //ES6
   console.log(`${JSON.stringify(message)} ${message[someArg]} ${someArg} ${message.bob}`);
   //ES5
   console.log(JSON.stringify(message) +  " " + message[someArg] + " " + someArg + " " + message.bob);

}

Now, on calling someFunction('bob'), the output is:

{"bob":"Hello bob","mike":"Hello mike","tara":"Hello tara"} Hello bob bob Hello bob
Sign up to request clarification or add additional context in comments.

Comments

0

When using message.someArg you are "telling" attribute someArg or your message Object.

What you have to use is message[someArg] to get the dynamic property.

Comments

0

You have to use the [] notation, where obj[key] is the same as obj.key, but key can be a variable.

function someFunction(someArg) {

  var message = {
    bob: "Hello bob",
    mike: "Hello mike",
    tara: "Hello tara"
  }

  console.log(JSON.stringify(message) + " " + message[someArg] + " " + someArg + " " + message.bob);

}


someFunction("mike");

Comments

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.