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":"John@gmail.com"
},
{
"id":2,
"name":"Sam",
"email":"Sam@gmail.com"
},
{
"id":3,
"name":"Dan",
"email":"Dan@gmail.com"
}
]
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 ?
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>`;
});
You're trying to access the value on the parent array as oppose to each individual element in the array.
Try this instead:
users.map(user =>
`<ul>
<li>ID: ${user.id} </li>
<li>Name: ${user.name}</li>
<li>Email: ${user.email}</li>
</ul>`
);
Template literal should be of form ${i.id}
etc. You want to render template with values of processed items not the users
array. users
does not have properties id
or email
, so these are undefined
const users = [ { "id":1, "name":"Jon", "email":"John@gmail.com" }, { "id":2, "name":"Sam", "email":"Sam@gmail.com" }, { "id":3, "name":"Dan", "email":"Dan@gmail.com" } ]; const output = users.map(({ id, name, email }) => { return `<ul> <li>ID: ${id} </li> <li>Name: ${name}</li> <li>Email: ${email}</li> </ul>` }); console.log(output);
In your lambda, you are using i
to reference each user, thus, you need to use i.id
, i.name
, etc.:
let users = [ { "id":1, "name":"Jon", "email":"John@gmail.com" }, { "id":2, "name":"Sam", "email":"Sam@gmail.com" }, { "id":3, "name":"Dan", "email":"Dan@gmail.com" } ]; let output = users.map((i) => { return `<ul> <li>ID: ${i.id}</li> <li>Name: ${i.name}</li> <li>Email: ${i.email}</li> </ul>`; }); console.log(output);
You should use 'i' variable to access to object properties:
users.map((i) => {
return `<ul>
<li>ID: ${i.id} </li>
<li>Name: ${i.name}</li>
<li>Email: ${i.email}</li>
</ul>`
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.