Skip to content
Advertisement

Javascript forEach return value interpolated into string

stack_html += "<div class='co-stack-layer-title'>Application and Data" +
                        "<div class='row'>" +
                          response['Application and Data'].forEach(generateStackItem) + 
                        "</div>" +
                      "</div>";
stack_html += "<div class='co-stack-layer-title'>Business Tools" +
                        "<div class='row'>" +
                          response['Business Tools'].forEach(generateStackItem) + 
                        "</div>" +
                      "</div>";
stack_html += "<div class='co-stack-layer-title'>DevOps" +
                        "<div class='row'>" +
                          response['DevOps'].forEach(generateStackItem) + 
                        "</div>" +
                      "</div>";
stack_html += "<div class='co-stack-layer-title'>Utilities" +
                        "<div class='row'>" +
                          response['Utilities'].forEach(generateStackItem) + 
                        "</div>" +
                      "</div>";

function generateStackItem(element, index, array) {
    var stack_item_html = "";
    stack_item_html += "<div class='co-service'>" +
                     "<a href='" + element['canonical_url'] + "' class='each-service hint hint--top' data-hint='" + element['name'] + "' data-align='left'>" +
                       "<img src='" + element['image_url'] + "'>" +
                     "</a>" +
                   "</div>";

    console.log(stack_item_html);
    return stack_item_html;                       
}

I’m trying to use a forEach iteration on a javascript object, and it seems I cannot interpolate the return value into the string addition.

<div class='co-stack-layer-title'>Application and Data<div class='row'>undefined</div></div><div class='co-stack-layer-title'>Business Tools<div class='row'>undefined</div></div><div class='co-stack-layer-title'>DevOps<div class='row'>undefined</div></div><div class='co-stack-layer-title'>Utilities<div class='row'>undefined</div></div>

Advertisement

Answer

forEach returns undefined. Use map+join.

"abc" + response['Utilities'].map(generateStackItem).join("") + "def";
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement