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

JavascriptJqueryObjectVariablesProperties

Javascript Problem Overview


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");
}

Javascript Solutions


Solution 1 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPruitIgoeView Question on Stackoverflow
Solution 1 - JavascriptSkilldrickView Answer on Stackoverflow