JavaScript - Using a variable to refer to a property name?

61,240

If you want to use a variable property name, use subscript syntax:

var fieldname = 'test';

//These two lines are equivalent as long as fieldname is 'test':
gridObject[fieldname] = fieldvalue;
gridObject.test = fieldvalue
Share:
61,240
PruitIgoe
Author by

PruitIgoe

I have been a soldier, a journalist, an archaeologist, a graphic/web designer and am now programmer, working in web front end, building desktop applications and mobile app development. I prefer to work in objective-c or if it is to be a cross-platform app then Appcelerator's Titanium.

Updated on April 03, 2021

Comments

  • PruitIgoe
    PruitIgoe about 3 years

    I am creating my own object:

    gridObject = new Object();
    

    I am then using jquery to pull the contents of list item tags, which themselves are filled with

    tags that have specific class names:

    <li row="1"><p class="department" rowitem="department">Photography</p>...</li>
    

    I am pulling them using this code:

    //make object from results
    gridObject = new Object();
            
    //get all the rows
    var rowlist = $('li[row]');
            
    for(var r=0; r<rowlist.length; r++) {
                
        //make gridObject row element here
                
        //get the row content
        var thisrow = $(rowlist[r]).html();
    
        //get all the p tags
        var rowitems = $(thisrow + 'p.[rowitem]');
                
        //get field name
        for(var ri=0; ri<rowitems.length; ri++) {
        if (r < 2) { //this is temporary just for testing
             var fieldname = $(rowitems[ri]).attr('rowitem');
             var fieldvalue = $(rowitems[ri]).html();
        }
        }
    

    Ia m getting hung up passing this into my object. Two questions. Can an object property be made with a variable name, like so

    griObject.fieldname = fieldvalue;
    

    and can the objects have parent/child relationships such as:

    gridObject.r.fieldname = fieldvalue; 
    

    in this case both r and fieldname would be variables. Or should I just be working associative arrays to achieve something similar?

    This is in answer to a follow up question I posted below: "Is there a print_r equivalent in javascript" - you can use iterator, a bit more typing but does the trick:

    //loop through search data
    var it = Iterator(filteritems); 
    for(var pair in it) { 
        console.log("key:" + pair[0] + ", value:" + pair[1] + "\n");
    }