Reputation: 5294
having a difficult time converting a Jquery map function to an arrow function.
here is the fiddle.
// find elements
$('button').click(function(e) {
let answerArray = $(`[name="foo"]`).map(function() {
return $(this).val();
}).get();
console.log(answerArray)
let answerArray2 = $(`[name="foo"]`).map(x => $(x).val()).get();
console.log(answerArray2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="foo">
<input name="foo">
<button>
enter
</button>
but I am receiving.
VM118 jquery.js:7977 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined at jQuery.fn.init.val (VM102 jquery.js:7977) at HTMLInputElement.$.map.x ((index):74) at VM102 jquery.js:194 at Function.map (VM102 jquery.js:443) at jQuery.fn.init.map (VM102 jquery.js:193) at HTMLButtonElement. ((index):74) at HTMLButtonElement.dispatch (VM102 jquery.js:5183) at HTMLButtonElement.elemData.handle (VM102 jquery.js:4991)
Upvotes: 0
Views: 965
Reputation: 133403
As per your code x refers to index not element thus you are getting the error.
Use correct callback
function arguments of .map()
.
Type: Function( Integer index, Element domElement ) => Object A function object that will be invoked for each element in the current set.
// find elements
$('button').click(function(e) {
let answerArray2 = $(`[name="foo"]`).map((i, x) => $(x).val()).get();
console.log(answerArray2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="foo">
<input name="foo">
<button>
enter
</button>
Upvotes: 4