What method to use to access multiple objects in an array?

Viewed 304

I'm new to javascript and still learning them.

So I was building a project where I want to display a multiple object, which I put it in an array, to the DOM. I am not sure what method to use to access the object inside the array.

<div class="container">
    <div class="hero">
        <h2>List of Names</h2>
    </div>

    <ul class="name-list"></ul>
</div>

This is my js file:

const nameList = document.querySelector('.name-list');

//List of Names
const john = {
    name: 'john',
    car: 'fiat',
    address: 'new york'
}
const mike = {
    name: 'mike',
    car: 'toyota',
    address: 'sydney'
}
const greg = {
    name: 'greg',
    car: 'nissan',
    address: 'melbourne'
}

//Store list of names in an array
const allNames = [
    john,
    mike,
    greg
]

function displayName (){

    //Not sure what methods to use to     
    return `
        <li>
            <p>Name: ${allNames.name}</p>
            <p>Car: ${allNames.car}</p>
            <p>Address: ${allNames.address}</p>
        </li>
    `
}

So I kind of want to display all the objects in the DOM. Is it necessary to put the objects in the array first? What methods do I use to return a list in the file? Or do you know any easier methods to display all the objects in the DOM?

Thank you so much for the help.

2 Answers

Maybe you can try something like this :

function showNameList() {
  const allNames = [
      {
          name: 'john',
          car: 'fiat',
          address: 'new york'
      },
      {
          name: 'mike',
          car: 'toyota',
          address: 'sydney'
      },
      {
          name: 'greg',
          car: 'nissan',
          address: 'melbourne'
      }
  ]
  var namelist = allNames.map(function (t, i) {
    return `<b>Name : </b> ${t.name}<br/><b>Car : </b> ${t.car}<br/><b>Address : </b> ${t.address}<br/><br/>`;
  })

  document.getElementById('name-list').innerHTML =
    '<li>' + namelist.join('</li><li>') + '</li>'
}

showNameList()
<div class="container">
    <div class="hero">
        <h2>List of Names</h2>
    </div>

    <ul id="name-list"></ul>
</div>

use map function to display them :

const values = allNames.map(item=>{
  return(
      <li>
            <p>Name: ${item.name}</p>
            <p>Car: ${item.car}</p>
            <p>Address: ${item.address}</p>
        </li>
  )
})
<div class="container">
    <div class="hero">
        <h2>List of Names</h2>
    </div>

    <ul class="name-list">
    {values}
    </ul>
</div>

Related