Wednesday, January 24, 2007

 

Making an Array of Objects

Every now and then I find myself having to rethink something I know I dealt with just recently but the details have slipped through my grasp. So this blog entry is an aide-memoire for me!

I'm working on a script where I want a function to read values from a table and return an array of objects that reflect the values in the table. I want each object to have this form:

{srcFnt:, srcStyl:, targFnt:, targStyl:}

So, the the loop looks like this (it starts at row 2 to skip over the heading info in the table):
    var List = new Array();
    for (var j = 2; myTable.bodyRowCount > j; j++) {
      if (myTable.rows[j].cells[0].contents == "") { break }
      
    }
So, if I get to that blank line, what do I do to create the object?

Well, there's nothing like writing a blog to trigger new ideas: previously, it never occurred to me to use a function to create the object directly. Let's see how this works:
    var List = new Array();
    for (var j = 2; myTable.bodyRowCount > j; j++) {
      if (myTable.rows[j].cells[0].contents == "") { break }
      List.push(getObject(myTable.rows[j]))
    }
  
  function getObject(theRow) {
    return {
      srcFnt:theRow.cells[0].texts[0].contents,
      srcStyl:theRow.cells[1].texts[0].contents,
      targFnt:theRow.cells[2].texts[0].contents,
      targStyl:theRow.cells[3].texts[0].contents
    }
  }
Well what do you know! That was easy. Much easier than what I did last time I tried to solve this problem.

Comments:
How can to make an array with 1000 rows, 2 columns
 
What is a column in this context? Are you talking about a table?
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?