Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 1

Leandro Severino
Leandro Severino
12,674 Points

Is there in anyway you can use for...in loop in an array of objects?

Is there in anyway you can use for...in loop in an array of objects?

3 Answers

Jesus Mendoza
Jesus Mendoza
23,289 Points

Sure, lets say we have an object.

let obj = {
   name: 'FirstObject',
   value: 'Object',
   length: 3
}

for (item in obj) {
   console.log(`${item}: ${obj[item]}`);
}

We say for each "item" (this can be any name) in obj (name of the obj you want to access) and then to access the property and property values we use "item" (the name given before) to access the property and obj[item] to access the property value.

Leandro Severino
Leandro Severino
12,674 Points

Hi! I've figured how to list all the properties of an object in an array. For example, we have 2 students with their own set of properties and we want to see their values.

var students = [ { name : "Mike", track: "track-a", achievements: 23, points : 400, },

{ name : "james", track: "track-a", achievements: 2, points : 21, },
]

students.forEach(myFunction);

function myFunction (item, index) {

for( var key in item ) { console.log(item[key]) } }

Jesus Mendoza
Jesus Mendoza
23,289 Points
let obj = [{
   name: 'FirstObject',
   type: 'Object',
   length: 3
},
{
   name: 'SecondObject',
   type: 'Object',
   length: 5
}];

obj.forEach(function(currentObj) {
   for (item in currentObj) {
      console.log(`${item}: ${currentObj[item]}`);
   }
});

I misunderstood your question, this would do