0

I have a javascript object that contains two arrays. Sometimes one of the arrays may be empty. I'm trying to loop through the object via a recursive function but I don't want any arrays that are empty or empty strings to enter the loop. What I have so far is producing the error Typeerror: obj.filter is not a function.

NOTE: obj is in this example has two arrays inside of it, but really, it could be anything that I pass into the function.

var obj = {
    selected: [ "value1", "value"2],
    unselected: []
}

function clearAndSetSelectElement($elem, obj, isEmpty) {
    if(isEmpty) $elem.empty(); //empty the select element if it isn't empty
    $.each(obj.filter(function(v){return v != null}), function() { //filter out empty arrays or empty strings
        if(this instanceof Array) clearAndSetSelectElement($elem, this, false); //if this is an array make recursive call
        $elem.append("<option />").val(this).text(this)); //append value to select element
    });
}
1
  • I think you're better off by using jQuery's $.filter() (api.jquery.com/filter) method, which works on all browsers.
    – Andy
    Jul 27, 2012 at 13:46

2 Answers 2

0

obj.filter is not a function, but obj.selected.filter should be (obj is an object, not an array).

It won't work in IE7 by default I guess, you'll either have to copy the polyfill from Mozilla Developer's Network (MDN) or use Modernizr.

2
  • the obj is a variable so it will not always be obj.selected. I could pass in anything really. I wanted to be able to filter out any array that was empty or any null values passed into the loop
    – bflemi3
    Jul 27, 2012 at 13:41
  • Yeah, I realized in the meanwhile, look at this question: stackoverflow.com/questions/5072136/…
    – Aadaam
    Jul 27, 2012 at 13:44
0

May be you can try this (if you want to populate a select with some options from an array)

HTML

<select id="sel"></select>​

JS

function setSelect(elem, obj)
{
    for(var o in obj)
    {
        if(obj[o] instanceof Array && obj[o].length)
        {
            $.each(obj[o], function(key, value) {   
                elem.append($("<option></option>").attr("value",value).text(value)); 
            });
        }
    }
}

Populate the selct using setSelect function

var obj = {
    selected: [ "value1", "value2"],
    unselected: []
}

var elem=$('#sel');            
setSelect(elem, obj);

DEMO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.