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
    });
}
bflemi3
  • 6,698
  • 20
  • 88
  • 155
  • I think you're better off by using jQuery's $.filter() (http://api.jquery.com/filter/) method, which works on all browsers. – Andy Jul 27 '12 at 13:46

2 Answers2

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.

Aadaam
  • 3,579
  • 1
  • 14
  • 9
  • 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 '12 at 13:41
  • Yeah, I realized in the meanwhile, look at this question: http://stackoverflow.com/questions/5072136/javascript-filter-for-objects – Aadaam Jul 27 '12 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.

The Alpha
  • 143,660
  • 29
  • 287
  • 307