How to acess property of object/subobject...

Discussion in 'Javascript' started by surfintheusa@yahoo.com, Jun 17, 2005.

  1. Guest

    Hi all,

    Given the following:

    var obj = new Object();
    obj.prop1 = 1;
    obj.prop2 = 2;
    obj.subobj = new Object();
    obj.subobj.prop3 = 3;

    I'd like to automatically access the right property given it's name
    like this:

    var propName = whatever; // Can be "prop1", "prop2" or "prop3".
    var propValue = obj["" or "subobj"][propName];

    Technically, in the case of "prop1" or "prop2" the first square
    brackets should disappear. Is there a way to do that?

    Thanks!
    Terry
     
    , Jun 17, 2005
    #1
    1. Advertising

  2. RobG Guest

    wrote:
    > Hi all,
    >
    > Given the following:
    >
    > var obj = new Object();
    > obj.prop1 = 1;
    > obj.prop2 = 2;
    > obj.subobj = new Object();
    > obj.subobj.prop3 = 3;
    >
    > I'd like to automatically access the right property given it's name
    > like this:
    >
    > var propName = whatever; // Can be "prop1", "prop2" or "prop3".
    > var propValue = obj["" or "subobj"][propName];
    >
    > Technically, in the case of "prop1" or "prop2" the first square
    > brackets should disappear. Is there a way to do that?


    Use a function to go down the list of accessors. The following expects
    to be passed an object as arg 0, then each accessor in correct order:

    function getValue(){
    var x = arguments;
    var i=0, v = x;
    while ( x[++i] ) { v = v[x]; }
    return v;
    }

    // Test based on obj above
    var w = 'prop1',
    x = 'prop2',
    y = 'subobj',
    z = 'prop3';

    alert(
    w + ': ' + getValue(obj, w) + '\n'
    + y + '.' + z + ': ' + getValue(obj, y, z) + '\n'
    + 'obj.' + x + ': ' + obj[x]
    );

    If the accessors are a single string (say 'subobj.prop3') then use
    split('.') to convert it to an array and proceed as above.


    --
    Rob
     
    RobG, Jun 17, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?Z2F1cmF2?=

    Uploading Data From MS Acess 2000 ti SQL server 2000

    =?Utf-8?B?Z2F1cmF2?=, Jan 9, 2006, in forum: ASP .Net
    Replies:
    2
    Views:
    816
    Mary Chipman [MSFT]
    Jan 9, 2006
  2. Dave

    const base subobject

    Dave, Apr 5, 2004, in forum: C++
    Replies:
    1
    Views:
    326
    Howard
    Apr 5, 2004
  3. Electric Co.
    Replies:
    3
    Views:
    425
    Electric Co.
    Aug 9, 2006
  4. Fraser Ross
    Replies:
    0
    Views:
    247
    Fraser Ross
    Apr 8, 2009
  5. shinedance
    Replies:
    0
    Views:
    358
    shinedance
    Oct 10, 2011
Loading...

Share This Page