user1801879
user1801879

Reputation: 822

Jquery.each throwing error: possible Json to string conflict

Hi i need to iterate over each title in this code. However, i'm getting some error in console that states cannot use 'in' operator. This code works fine when i pass an id that is coming from database. But i need to pass in a string, then it throws error right after each function is called. I can't figure out why, one thing i can think of is there is possible JSON/string conflic. How do i resolve that. Any help would be appreciated thanks.

   function getFilteredBySearch(searchString){      

              return priv.availablePrintables.filter(function(printableModel) {               
                var result = false;               
                var title = printableModel.getTitle();              
                  $.each(title, function(idx, id) {

                    if (id == searchString) {
                        result = true;
                        return false;   // break out of the 'each' loop
                    }                  
                })
                return result;  // return from the callback
            });
        }

RESOLVED:

The following worked!

  if ((printableModel.getTitle()).indexOf(searchString) > -1){
                result = true;
                console.log(result);
              }

Upvotes: 0

Views: 143

Answers (2)

lukaleli
lukaleli

Reputation: 3627

This is only made based on assumptions: probably sometimes getTitle method return string and sometimes returns array of strings (because you've pointed out that console logs out ["book"] when you get title). You can check what type of object it returns:

function getFilteredBySearch(searchString){      

      return priv.availablePrintables.filter(function(printableModel) {                            
        var title = printableModel.getTitle();
            if(typeof title == 'string'){
                //if it's string
                return (title == searchString);
            }else{
                //if it's array
                return (title.indexOf(searchString) != -1);
            }
    });
}

Upvotes: 1

user1864610
user1864610

Reputation:

I think you're trying to iterate over the collection, when the filter method already does that for you. You don't need jQuery to loop over a number of items, when you only have one to examine. Try this:

function getFilteredBySearch(searchString){      

    return priv.availablePrintables.filter(function(printableModel) {               

      return (searchString == printableModel.getTitle());              
    });
}

(I'm not that familiar with backbone.js, so I might have the syntax slightly wrong)

Upvotes: 2

Related Questions