JS how to map through Array in template literals

Cho Lin Tsai picture Cho Lin Tsai · Oct 3, 2017 · Viewed 9.8k times · Source

I ran into a problem and couldn't fix it today. For example, there is a json file text.json

[
  {
    "id":1,
    "name":"Jon",
    "email":"[email protected]"
  },
  {
    "id":2,
    "name":"Sam",
    "email":"[email protected]"
  },
  {
    "id":3,
    "name":"Dan",
    "email":"[email protected]"
  }
]

Now I want to use ajax to get this json file and here is the part doesn't work.

let output = users.map((i) => {
                    return `<ul>
                        <li>ID: ${users.id} </li>
                        <li>Name: ${users.name}</li>
                        <li>Email: ${users.email}</li>
                    </ul>`
                })

Where should I put the i in template literals ?

Answer

danwellman picture danwellman · Oct 3, 2017

Wouldn't it be:

let output = users.map((i) => {
    return `<ul>
              <li>ID: ${i.id} </li>
              <li>Name: ${i.name}</li>
              <li>Email: ${i.email}</li>
            </ul>`;
 });