Home > other >  Traversing trough array of objects in javascript
Traversing trough array of objects in javascript

Time:11-22

I'm kinda new in JavaScript, I know that there are different ways how to traverse array of objects, but I found a tutorial and didn't get this ${person.name} part. Code is:

let personData = [
  { name: "Dylan", age: 31 },
  { name: "Hannah", age: 17 },
  { name: "Dollan", age: 39 },
  { name: "Elle", age: 3 },
];

function loadTableData(personData) {
  for (let person of personData) {
    dataHtml  = `<tr><td>${person.name}</td><td>${person.age}</td></tr>`;
  }
}

I tried to understand what exactly is happening so I put `${personData.name}` to console and I get "undefined" = $3 My question is, why this works fine within for loop, but in console I'm getting undefined?

CodePudding user response:

From your example, personData is the array of objects, to access each item you access it inside the loop with a local variable person. Console will log undefined for ${personData.name} instead you can access an item of the array through index, try this ${personData[0].name} which will print the vale of name property in your first item.

CodePudding user response:

If you iterate over the personData object, you will get undefined with your given code. You can try the following:

personData.forEach(function (person ) {
     dataHtml  = `<tr><td>${person.name}</td><td>${person.age}</td></tr>`;
});
  • Related