I’m having some trouble with getting the value of an object in my array when the value is determined by a function instead of hard coded. In this example, I want to either iterate through the array to console.log the value of my “stats” object and not return the function I have there OR add to the existing function on each object in my array to console.log the value and again, not the function itself.
Here, my function returns the value in a text box as the value of the object “stats” in my array. Every time I try it either returns the function itself as the value or returns a “null” or only returns the value of the first object in my array.
Can someone please tell me what I am missing?
Thanks.
Here is my (full HTML) sample code with the "options" I have tried.
let users = [{
    name: "bob",
    stats: function() {
      return document.getElementById('option1').value;
    },
    code: "A1"
  },
  {
    name: "john",
    stats: function() {
      return document.getElementById('option2').value;
    },
    code: "A2"
  },
  {
    name: "karen",
    stats: function() {
      return document.getElementById('option3').value;
    },
    code: "A1"
  }
]
/* Option 1 */
console.log('firstRun');
users.forEach((user) => console.log(user.stats));
/* Option 2 */
console.log('secondRun');
for (let user of users) {
  console.log(user.stats)
}
/* Option 3 */
console.log('thirdRun');
var myArray = users.length;
for (i = 0; i < myArray; i++) {
  console.log(myArray.stats)
}<h2>Simple Object/Array Step Through</h2>
<input type="text" id="option1" value="box1">
<input type="text" id="option2" value="box2">
<input type="text" id="option3" value="box3">

stats()to run the function.statsjust returns the function itself.idof each element instead of the whole function again and again. Just store the id, and use it as a parametergetElementByIdnot find the element?. You’re not waiting for the DOM to be loaded. None of the options could ever result innull, but they might throw the “TypeError: cannot read property 'value' ofnull”.for (i = 0; i < myArray; i++)is missing theletkeyword. This means you are modifying the globali. The for-loop should also usemyArray[i].stats(notmyArray.stats) the array itself doesn't have astatsproperty.