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 trialLeandro Severino
12,674 PointsIs 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
23,289 PointsSure, 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
12,674 PointsHi! 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
23,289 Pointslet 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
Leandro Severino
12,674 PointsJesus Mendoza, thanks! I appreciate your help.
Leandro Severino
12,674 PointsLeandro Severino
12,674 PointsThanks for your answer. :)