returning from forEach javascript [duplicate]

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?

Answers:

Answer

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>

Answer

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") );

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.