0

I am trying to loop through an array of objects using a 'for' loop, and want to print the results in a template using Javascript. However, the data in the template comes back as undefined. Not sure where I am going wrong?

const people = [{
    name: "Martin",
    age: 45
  },
  {
    name: "Steve",
    age: 32
  }
];

for (let i = 0; i < people.length; i++) {
  let template = `
         <h2>${people.name}</h2>
         <p>${people.age}</p>
     `;
  document.write(template);
}

2
  • 2
    people[i].name Commented Jun 26, 2020 at 11:11
  • @adiga Thank you! I understand now. I just missed that bit. Suppose I have been using too much Vue.JS where you simply have something like {{person.name}} etc. Thanks for helping. It works and I now understand. Commented Jun 26, 2020 at 11:14

2 Answers 2

3

You need to use the index (i.e. i) to access the people array item:

const people = [
  {
    name: 'Martin',
    age: 45,
  },
  {
    name: 'Steve',
    age: 32,
  },
];

for (let i = 0; i < people.length; i++) {
  let person = people[i];
  let template = `
       <h2>${person.name}</h2>
       <p>${person.age}</p>
   `;
  document.write(template);
}
Sign up to request clarification or add additional context in comments.

Comments

3

You're not accessing the current element of the array instead your accessing people.name and people.age which are both undefined. You need to change it to:

for(let i = 0; i < people.length; i++) {
    const template = `
         <h2>${people[i].name}</h2>
         <p>${people[i].age}</p>
     `;
     document.write(template);
}

Even simpler is to use a modern for ... of-loop:

for(const currPerson of people) {
    const template = `
         <h2>${currPerson.name}</h2>
         <p>${currPerson.age}</p>
     `;
     document.write(template);
}

1 Comment

Love the second approach. Thanks for helping!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.