Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Using a variable to refer to a property name? [duplicate]

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"); } 
like image 753
PruitIgoe Avatar asked Jan 14 '11 18:01

PruitIgoe


People also ask

How do you set an object property with variables?

Use computed property names to set an object's property name from a variable in TypeScript, e.g. const obj: Person = {[myVar]: 'Tom'} . The computed property names feature allows us to dynamically determine the property names of an object.

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.

Are properties variables in JavaScript?

Introduction. JavaScript is an interpreted, object-oriented language that has two main data types: primitives and objects. This data within JavaScript is contained as fields (properties or variables) and code (procedures or methods).


1 Answers

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 
like image 121
Skilldrick Avatar answered Sep 28 '22 04:09

Skilldrick