Array of objects

Stack overflow has this example of looping trought js array of objects…

var person = [];
person[0] = {
    firstName : "John",
    lastName : "Doe",
    age : 60
};
var i, item;
for (i = 0; i < person.length; i++) {
    for (item in person[i]) {
        document.write(item + ": " + person[i][item] + "<br>");
    }
}

Which prints each property of object, How would I extract (print) only “age” property?

Hi there, I believe you would do it in the following way:

var person = [];
person[0] = {
    firstName : "John",
    lastName : "Doe",
    age : 60
};
var i, item;
for (i = 0; i < person.length; i++) {
    document.write("age: " + person[i].age + "<br>");
}
1 Like

Yeah that worked.

Thanks

1 Like

If he wants to do it in a more modern manner using ES6, it would be something like:

var person = [
  {
    firstName : "John",
    lastName : "Doe",
    age : 60
  }
];
document.write(person
  .map(personInfo => personInfo.age)
  .map(age => `age: ${age}<br>`)
);
2 Likes

I am having a problem where I am looping trought array of persons…something like this…

   for (var i = 0 ; i < persons.length; i++){

      //do something
      console.log (print each object with its properties) // this outputs each object with its properties no problem

       someOtherObject.addListener('click' function(){
              console.log (here it prints properties of the last object in the loop) //Where are other objects
       });
 
  }//end of for loop

What am I doing wrong here?

EDIT: I do have “click” trigger just mistyped here. I adjusted pseudo code above

addListener

The addListener function takes 2 parameters. The trigger and the function. You havent declared a trigger.

I found this post on SOF which helped me resolve the problem. Link here Adding click events while in the loop

Part of the post that helped me is below…

So what’s happening here is that you are keeping the variable ‘td’ in scope for the event listener function. There is only 1 instance of ‘td’, and that is getting updated each time the for loop iterates. Thus, when the for loop finished, the value of td is now set to the element ‘#td7’ and your event handler is simply logging the current value of td.

In the example above, you could simply log ‘this’

var td;
for (var t=1;t<8;t++){
    td = document.getElementById('td'+t);
    if (typeof window.addEventListener==='function'){
      td.addEventListener('click',function(){
        console.log(this);
      });
    }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.