Sam Driver
Sam Driver

Reputation: 92

How to use an object property as a function argument?

SOLUTION

Thanks to vadim. I had to change months[i].anArray[b] to months[i][anArray][b]

I have an array of months, which contains an object for each month. Each month has a number of properties, including arrays, for example:

months[0].consumptionPerHour returns 24 values which can be accessed with months[0].consumptionPerHour[0-23]

I am attempting to create a function which creates a table, having the name of the table and the name of the array I wish to access as arguments with the function, like so:

function tableMaker(tableName, anArray) {
  $("#outputs").append(
    "<table id='table" + totalTables + "'>"
    "<tr id='header" + totalTables + "'><td>" + tableName + "</td>"
  );
  for(i=0;i<12;i++) {
    $("#header" + totalTables).append("<td>" + months[i].shortName + "</td>");
  }
  for(b=0;b<24;b++) {
    $("#table" + totalTables).append(
      "<tr id='table" + totalTables + "row" + b + "'><td>" + hours[b] + "</td>"
    );
    for(i=0;i<12;i++) {
      $("#table" + totalTables + "row" + b).append("<td>" + months[i].anArray[b] + "</td>");
    }
  }
}

For some reason, if I pass a property name that I know exists as an argument, for example, tableMaker('Consumption', consumptionPerHour), it simply returns the following:

Uncaught ReferenceError: consumptionPerHour is not defined
    at <anonymous>:1:22

However, this is returned via console:

months[0].consumptionPerHour
(24) [0.1567002086212712, 0.1567118400503239, ...]

months[0].consumptionPerHour[0]
0.1567002086212712

Upvotes: 1

Views: 78

Answers (2)

hajile78
hajile78

Reputation: 167

It looks like the 'consumptionPerHour' is an array within the 'months' array. And it also looks like you have access to the months array in the function without having to pass it in as a parameter. So the function would look something like this:

function tableMaker(tableName) {
  $("#outputs").append(
    "<table id='table" + totalTables + "'>"
    "<tr id='header" + totalTables + "'><td>" + tableName + "</td>"
  );
  for(i=0;i<12;i++) {
    $("#header" + totalTables).append("<td>" + months[i].shortName + "</td>");
  }
  for(b=0;b<24;b++) {
    $("#table" + totalTables).append(
      "<tr id='table" + totalTables + "row" + b + "'><td>" + hours[b] + "</td>"
    );
    for(i=0;i<12;i++) {
      $("#table" + totalTables + "row" + b).append("<td>" + months[i].consumptionPerHour[b] + "</td>");
    }
  }
}

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

To access an object property using a variable you need to use [] notation and the variable needs to be a string

So I think what you want is

tableMaker('Consumption', 'consumptionPerHour')

Then in function use:

months[i][anArray][b]

Upvotes: 2

Related Questions