www.webdeveloper.com
Results 1 to 2 of 2

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

  1. #1
    Join Date
    Mar 2014
    Posts
    4

    Question 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?

  2. #2
    Join Date
    Mar 2009
    Posts
    468
    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.
    should read

    Code:
    return operator[key_value]; // where key value can be age.
    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.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles