0

I'm trying to write a generic script to loop thru an array of objects and return the values of the properties at each cycle. Rather than access the properties via

myArray[0].someProperty;
myArray[0].anotherProperty;

I'm storing property names in an array using Object.keys(myArray[0]). However at runtime I get TypeErrors. Could anyone tell me what I'm doing wrong? Or is there a way I can find out more on what TypeError means in this context? My sample code is below:

// Film Class
function Film(title, year, genre)
{
  this.title = title;
  this.year = year;
  this.genre = genre;
}

function Main()
{
  var films = [];

  films.push(new Film("Furious Seven", 2015, "Action"));
  films.push(new Film("The Matrix", 1999, "Sci Fi"));
  films.push(new Film("Invictus", 2009, "Drama"));

  var headers = Object.keys(films[0]);

  Logger.log(headers[0]);          // title
  Logger.log(films[0].title);      // Furious Seven
  Logger.log(films[0].headers[0]); // TypeError: Cannot read property "0" from undefined.
  Logger.log(films[0].(headers[0])); // TypeError: [object Object] is not an XML object.
}

1 Answer 1

1

When trying to extract the value of an object's property using a variable to reference the property's key, the variable representing the key should be enclosed in square brackets without the dot

Logger.log(films[0][headers[0]]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Sign up to request clarification or add additional context in comments.

1 Comment

Ahah. Ok I've never seen bracket notation in any languages before. Thanks for the solution + documentation ScampMichael

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.