0

I am trying to search for a string contained in an object array.

image_array = [
            {image: '/assets/monkey-face.jpg', link_url: '/animal/showit?animal=Monkey'},
            {image: '/assets/tiger-face.jpg', link_url: '/animal/showit?animal=Tiger'} 

]

Will not find the string 'monkey' or 'tiger' in the url parameter showit or the image.

    image_array.IndexOf 
jQuery.inArray

If I try to loop through the array/object and search for the string I get:

"Object #<Object> has no method 'search'"

Where am I going wrong - why does it return -1 when the object has the string in it?

2
  • Have you tried the src attribute of your image? Commented Dec 3, 2013 at 6:11
  • Well, error seems clear. Your array contains objects not strings, and objects don't have a method search Commented Dec 3, 2013 at 6:12

3 Answers 3

5

Try this:

for(var i = 0; i < image_array.length; i++){
  if(image_array[i].link_url.indexof("Monkey") != -1){
    // Item found
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Array does not have search method - it is for string. Try $.grep()

var result = $.grep(image_array, function(item){
    return item.link_url.indexOf('Monkey') >= 0;
})

//result will be an array with all items having `Monkey` in link_url
console.log(result)

Demo: Fiddle

1 Comment

Thanks Arun. I needed the index of the object in the array so the accepted answer worked best for me.
0

Since you are trying to check whether a string is contained inside the object values, assuming the string is not used as any key values, try the following:

 return JSON.stringify(image_array).indexOf("monkey") > 0

Hope this helps :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.