Nick
Nick

Reputation: 495

Array.map() Producing Strange Results

I have a set of textarea elements on page that all share the same class name.

I'm attempting to retrieve their values into an array like:

var deal_dcon_recs = $('.deal_dcon_text').map((i, {value}) => value);

Seems pretty simple to me.

But I'm experiencing the strangest results.

The array I get is an array of the html objects, not just the string value.

From this troubleshooting code:

var deal_dcon_recs = $('.deal_dcon_text').map((i, {value}) => {console.log('value', value); return value;});
console.log('deal_dcon_recs', deal_dcon_recs);

I get this output:

enter image description here

What in the world am I missing here?

Upvotes: 1

Views: 154

Answers (3)

ikiK
ikiK

Reputation: 6532

Just a another way of using loop and plain JS, to simplify things...

let result = []
document.querySelectorAll(".deal_dcon_text").forEach(el => result.push(el.value))
console.log(result)
<textarea name="textarea" class="deal_dcon_text" placeholder="Enter the text...">1</textarea>
<textarea name="textarea" class="deal_dcon_text" placeholder="Enter the text...">2</textarea>
<textarea name="textarea" class="deal_dcon_text" placeholder="Enter the text...">3</textarea>

Or using map and spread operator ...:

let result = [...document.querySelectorAll(".deal_dcon_text")].map((i) => i.value);

console.log(result)
<textarea name="textarea" class="deal_dcon_text" placeholder="Enter the text...">1</textarea>
<textarea name="textarea" class="deal_dcon_text" placeholder="Enter the text...">2</textarea>
<textarea name="textarea" class="deal_dcon_text" placeholder="Enter the text...">3</textarea>

BTW spread operator will work on jquery also:

let result = [...$(".deal_dcon_text")].map((i) => i.value);

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your current logic within map() is correct. The issue is because you're missing a call to get() after the map() in order to return the array that's generated, not a jQuery object:

var deal_dcon_recs = $('.deal_dcon_text').map((i, {value}) => value).get();
console.log(deal_dcon_recs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="deal_dcon_text">Lorem ipsum</textarea>
<textarea class="deal_dcon_text">Dolor sit</textarea>
<textarea class="deal_dcon_text">Amet consectetur</textarea>
<textarea class="deal_dcon_text">Adipscing elit</textarea>

Upvotes: 2

Frenchy
Frenchy

Reputation: 17007

For me map work with an array and selector is an object:

you could try:

$('.deal_dcon_text').toArray().map....

Upvotes: 0

Related Questions