Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip an element with jQuery's $.map

I have a jQuery object obj that encapsulates a set of input elements.

I am using this code in order to make an array out of each element's value :

$.map(obj, function(elem, i){
    return $(elem).val();
});

The problem is that sometimes some of the input fields contain invalid values and i would like to skip them in the process of creating the array. Doing a simple return false doesn't seem to skip the element but instead inserts a false in the array.

I would like to know if there is a way to actually do that without using .each explicitly.

like image 299
Dany Khalife Avatar asked Jun 16 '13 20:06

Dany Khalife


2 Answers

Since it's an jQuery collection, you can execute .map directly and then use .get so that it becomes an array.

var values = obj.map(function(){
    return this.value ? this.value : null;
}).get();

Note: The above check will return any value that isn't falsey.

See test case on jsFiddle.

like image 173
mekwall Avatar answered Sep 28 '22 01:09

mekwall


I should have tried returning nothing (void) that did the trick, don't know why this didn't come across my head earlier.

In case you want to do the same, here is the fix:

$.map(obj, function(elem, i){
    if($(elem).val().length == 0) return;

    return $(elem).val();
});

EDIT

I just tested the length here and omitted to the validation code in order stay on the same subject

like image 37
Dany Khalife Avatar answered Sep 28 '22 01:09

Dany Khalife