/    Sign up×
Community /Pin to ProfileBookmark

How to convert a string to a variable and use it to call a map value? (with Node.js)

Greetings to all! I will go straight to the point.

I am using node.js engine to write javascript code and debug. I have created a map with some values and I want to use the key_value content passed to the function to call a value from this map.

Ideally:
E.g., If key_value= “age”
return Students[“Mark”].age

Originator.prototype.student= function(originator_name, key_value){ // key_value=”age”
var Students = {
“Mark”: {
age: 23,
hair_color: “brown”,
height: 1.78
},
“Tom”: {
age: 19,
hair_color: “black”,
height: 1.74

},
“Nick”: {
age: 26,
hair_color: “blonde”,
height: 1.78
}
};

var operator = Students[“Mark”];
return operator.key_value; // where key value can be age.
};

I tried print out the Node.js global function below to convert the string “age” to a variable and use it as a key:

console.log(Students[“Mark”].global[key_value]);

but I get this error:

console.log(Students[“Mark”].global[key_value]);
^
TypeError: Cannot read property ‘age’ of undefined.

Does anybody know how to do this?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@TcobbMar 03.2014 — I really don't know about the rest of your code, but the line:

[CODE]return operator.key_value; // where key value can be age.[/CODE]

should read

[CODE]return operator[key_value]; // where key value can be age.[/CODE]

When you use the "dot" notation its strictly literal, and your objects don't have a property named "key_value." If you use the square bracket notation you can use a variable, which is what you want to do.
×

Success!

Help @lefteris80 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...