Megarobo
Megarobo

Reputation: 3

Use javascript function parameter to get value from object

I have the following code:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj.x);
};

When I run myFunction(apples) I don't get an alert saying five, but I get an alert saying undefined.

How do I get the result I want by using the function parameter x with the object myObj

The result I want is it to say 'five' instead of 'undefined'.

Upvotes: 0

Views: 705

Answers (3)

DRD
DRD

Reputation: 5813

You have to pass the property name as a string. And within a function use bracket notation ([]) for access instead of using a dot (.).

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

myFunction("apples");

Upvotes: 1

Pal R
Pal R

Reputation: 534

Use [] notation:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

myFunction('apples')

Upvotes: 2

Superdrac
Superdrac

Reputation: 1208

For getting a property with a string, you need to use brackets myObj["name"]

Look at this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Correct code:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

Upvotes: 2

Related Questions