Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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");
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!