1

i have the following code:

options.forEach((option) => {
  return(option.get('template_name'))
})

where options contains a list of 2 maps

I expect this to return the template name, but instead I get 2 Why is this? How can I return from a forEach function in javascript?

2
  • can you share options object ? Commented Sep 14, 2017 at 15:56
  • Can you clarify what you expect to return? A single template name, or a list of template names from each "option" in the array? If the former, Jonas w's answer will suffice, if the latter use .map(). Commented Sep 14, 2017 at 16:00

2 Answers 2

3

forEach does not return. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/forEach#Return_value

Use map instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/map#Return_value

Also, to use map options must be an array.

Check out this example.

var options = Array.from(document.getElementById('selections').options),
    newOptions = options.map(function(item){
        return item.value
    });

console.log(newOptions);

document.getElementById('results').insertAdjacentHTML('afterbegin', newOptions.reduce((a,b) => a.concat(`${b} `), ' '));
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>returning from forEach javascript</title>
</head>
<body>

    <select id="selections">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
    
    <div id="results"></div>
    
</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

1

Thats what a gold old for loop is good for:

 for(var option of options){
    return option.get("template_name");
 }

Which equals:

 return options[0].get("template_name");

Or getting all names:

 const tnames = options.map( option => option.get("template_name") );

3 Comments

So why the loop in the first place?
@baao i bet the op left out some kind of if...
fair enough... :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.