Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top