Dynamic access of an object variable

Discussion in 'JavaScript' started by knapsack3, Sep 28, 2007.

  1. #1
    Hi,

    I have a JSON object whose structure is like this:

    The name of the object is 'Emp' and the attributes are:
    name
    age
    sex
    department
    address

    I pass this JSON object to a method in javascript and set it to a local variable (say tmpObj)
    Now I access the tmpObj's attributes dynamically from a javascript.

    I tried
    a = tmpObj.eval(fieldname);
    a = tmpObj[fieldname]

    but all these don't work and eval() throws an error in IE.

    Pls let me know your comments.

    Thanks.
     
    knapsack3, Sep 28, 2007 IP
  2. knapsack3

    knapsack3 Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I have found a solution for this. We can use

    tmp = eval( "(tmpObj." + fieldname+ ")");

    This will fetch the value dynamically
     
    knapsack3, Sep 28, 2007 IP
  3. flaviocrispim

    flaviocrispim Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi, knapsack3.

    There is one more step to do when working with json.
    Json is a notation of an object, so you must eval the entire json before passing to another functions. To eval the entire object you need to use json string between (), just like you did in your workaround.

    The big difference is that you don´t need to eval by object property, but by object. Now anything will work as you expected.

    Example:

    function aFunction(){
    var emp = eval("("+req.responseText+")");
    anotherFunc(emp);
    }

    function anotherFunc(tmpObj){
    // Both are valid.
    a = tmpObj.fieldname;
    a = tmpObj[fieldname];
    }
     
    flaviocrispim, Jan 26, 2008 IP