JS how to map through Array in template literals
12,304
Solution 1
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>`;
});
Solution 2
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>`
);
Solution 3
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":"[email protected]"
},
{
"id":2,
"name":"Sam",
"email":"[email protected]"
},
{
"id":3,
"name":"Dan",
"email":"[email protected]"
}
];
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);
Solution 4
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":"[email protected]" },
{ "id":2, "name":"Sam", "email":"[email protected]" },
{ "id":3, "name":"Dan", "email":"[email protected]" }
];
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);
Comments
-
Cho Lin Tsai almost 2 years
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 ?
-
danwellman over 6 yearshappy to help :)
-
Mörre over 6 years@ChoLinTsai Please declare an answer then, so that others browsing the list of issues know that your has already been solved :-) The answer from Andrzej Smyk has the advantage of giving you bette naming, you should not use "i" because by convention that is used for numeric indexes. That is programmer culture, not technical, but it helps when people work together to stick to such conventions when you have no reason not to.
-
Mörre over 6 yearsGood idea to rename OPs
i
touser
.