0

I have a for loop and I would like to tap into an object inside the array I am looping. Specifically I would like to tap into the "Name" section of my objects to only console.log the names, not the whole array. This is the code... I am doing this with Mongoose but I don't think it has anything to do with my problem, I just wanted to add it tho.

    const newCustomerNum2 = new customerList({
    name: "John",
    age: 32
    });


customerList.find(function(err, customers) {
if (err) {
 console.log(err);
} else {

for (var i = 0; i<customers.length; i++){
     console.log(customers.name);
  }
}
});

1 Answers1

1

What is happening in your for loop, is that you are looping over the indices of your array. Let's say you array has 3 elements, the for loop would be called with i = 0, then i = 1, then i = 2.

This index can be used to reference an object in your array.

When you are calling customers.name you are trying to access the property name on the array rather than the data in it. If you want to access the objects inside your array, use the subscript expression:

customers[i] where 0 < i < customers.length.

That way, you can use console.log(customers[i].name) in your loop.

In addition, you could simply use the for ... of expression, which iterates over the elements of an array:

for (let customer of customers) {
    console.log(customer.name);
}
KSR
  • 387
  • 2
  • 10
  • Awesome! That was a very quick answer. I just tried it and it fixed the issue. I appreciate you getting out of your way and helping people that are learning and don't have the knowledge you have. –  Jul 20 '20 at 21:06
  • Great ! You are welcome, we've all been there, let's make it easier for the others :). – KSR Jul 20 '20 at 21:08