JavaScript - Loop Through Array Directly In Multi Line String and Include Values

Viewed 563

Let's say I have an array called users.

const users = ["userOne", "userTwo"];

Within an ES6 multi-line string, I would like to loop through the array and include the values of the users array within the multi-line string.

I have tried giving it a go using the following code snippet:

const data = `

Hello,

The following users exist within the users array:

- ${users.forEach((item) => item)},
`

The expected outcome I would like it something like this:

Hello,

The following users exist within the users array:

- userOne
- userTwo

What would I need to do to loop through the array and include the values within the string?

4 Answers

You could map the items with some formatting.

const users = ["userOne", "userTwo"];
const data = `Hello,

The following user${users.length > 1 ? 's' : ''} exist within the user's array:

${users.map(item => `- ${item}`).join(',\n')}`

console.log(data);

You could try:

const users = ["userOne", "userTwo"];

const data = `Hello, The following users exist within the users array:
${users.map((user) => {
    return '- ' + user + '\n';
})}`

console.log(data);

Use map instead of forEach and join with delimitter '- '

const users = ["userOne", "userTwo"];


const data = `

Hello,
The following users exist within the user's array:

- ${users.map(item => item +'\n').join('- ')}`;

console.log(data)

Using users.map() instead of users.forEach(), because map returns a new array, forEach doesn't.

Related