24

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>"           
    })}
    `;
1

2 Answers 2

61

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.

8
  • 1
    I think there's like 15 minutes in which you cannot accept
    – mdatsev
    Jan 21, 2018 at 15:21
  • 1
    @nitte93user3232918 I need to wait 9 min
    – Steven
    Jan 21, 2018 at 15:22
  • 2
    I'd suggest that it would be better form to move the code out to a function for neatness and so that a separate template literal can be used inside the callback.
    – user8897421
    Jan 21, 2018 at 15:28
  • 1
    @rockstar: Yes, I'd agree wholeheartedly. Jan 21, 2018 at 15:32
  • 1
    @GalibHasanov - Because the result of calling forEach is always undefined, but the result of calling map is an array with the mapped contents. Dec 1, 2018 at 17:13
19

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.

3
  • 2
    It's more useful, when you see a minor omission like that, to comment and let the answerer know. (I've been doing too much React lately!) SO is meant to be collaborative. Dec 1, 2018 at 17:12
  • FYI anyone reading these comments on stephledev's answer, the fix is integrated into the accepted answer so there is nothing to see here. ;) Nov 5, 2019 at 8:58
  • Exactly what i was looking for in literals.
    – sg28
    Oct 29, 2021 at 2:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.