Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Literals with a ForEach in it

Is it possible to return a string value in ForEach in a Template literal so it will be added in that place? Because if I log it it returns undefined. Or is that like I typed not possible at all?

return `<div>
                <form id='changeExchangeForViewing'>
    <label for='choiceExchangeForLoading'>Change the exchange</label>
    <div class='form-inline'>
    <select id='choiceExchangeForLoading' name='choiceExchangeForLoading' class='form-control'>

    ${Object.keys(obj).forEach(function (key) {
        return "<option value='" + key + "'>" + obj[key] + "</option>"           
    })}
    `;
like image 484
Steven Avatar asked Jan 21 '18 15:01

Steven


People also ask

Can you concatenate template literals?

When you use regular template literals, your input is passed to a default function that concatenates it into a single string. An interesting thing is that you can change it by preceding the template literal with your function name that acts as a tag. By doing it, you create a tagged template.

What are template literals give an example?

Template literals (template strings) allow you to use strings or embedded expressions in the form of a string. They are enclosed in backticks `` . For example, const name = 'Jack'; console. log(`Hello ${name}!`); // Hello Jack!

What is `` in JS?

Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.

What character is used to signify a template literal?

To create a template literal, instead of single quotes ( ' ) or double quotes ( " ) quotes we use the backtick ( ` ) character.


2 Answers

No, because forEach ignores the return value of its callback and never returns anything (thus, calling it results in undefined).

You're looking for map, which does exactly what you want:

return `<div>
    <form id='changeExchangeForViewing'>
        <label for='choiceExchangeForLoading'>Change the exchange</label>
        <div class='form-inline'>
            <select id='choiceExchangeForLoading' name='choiceExchangeForLoading' class='form-control'>
                ${Object.keys(obj).map(function (key) {
                    return "<option value='" + key + "'>" + obj[key] + "</option>"
                }).join("")}
`;

Note that after mapping, the code uses .join("") to get a single string from the array (without any delimiter). (I forgot this initially — been doing too much React stuff — but stephledev pointed it out in his/her answer.)

That said, it might be easier to read if you break it up, and you can use an arrow function rather than a traditional function, perhaps with another template literal:

const options = Object.keys(obj).map((key) =>
    `<option value='${key}'>${obj[key]}</option>`
);
return `<div>
    <form id='changeExchangeForViewing'>
        <label for='choiceExchangeForLoading'>Change the exchange</label>
        <div class='form-inline'>
            <select id='choiceExchangeForLoading' name='choiceExchangeForLoading' class='form-control'>
                ${options.join("")}
`;

Finally, I'll mention Object.entries, which gives you an arrow of [key, value] arrays, which you might want to use in mapping the options (or not, Object.keys is fine too):

const options = Object.entries(obj).map((key, value) =>
    `<option value='${key}'>${value}</option>`
);
return `<div>
    <form id='changeExchangeForViewing'>
        <label for='choiceExchangeForLoading'>Change the exchange</label>
        <div class='form-inline'>
            <select id='choiceExchangeForLoading' name='choiceExchangeForLoading' class='form-control'>
                ${options.join("")}
`;

Side note: That's not a "string literal," it's a template literal.

like image 101
T.J. Crowder Avatar answered Oct 13 '22 00:10

T.J. Crowder


Since map() returns an array, @T.J. Crowder's answer will produce invalid HTML as the toString() method of an array will be called inside the template literal, which uses commas to delimit the array. To fix this, just append join('') to explicitly use no delimiter:

${Object.keys(obj).map(key => (
    `<option value="${key}">${obj[key]}</option>`
)).join('')}

Also, you can use template literals inside the map itself.

like image 40
stephledev Avatar answered Oct 13 '22 00:10

stephledev