在对象数组中搜索字符串

Search Object Array for string

本文关键字:搜索 字符串 数组 对象      更新时间:2024-02-28

我正在尝试搜索对象数组中包含的字符串。

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

在url参数showit或图像中找不到字符串"monkey"或"tiger"。

    image_array.IndexOf 
jQuery.inArray

如果我试图循环遍历数组/对象并搜索我得到的字符串:

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

我哪里错了?为什么当对象中有字符串时,它会返回-1?

试试这个:

for(var i = 0; i < image_array.length; i++){
  if(image_array[i].link_url.indexof("Monkey") != -1){
    // Item found
  }
}

数组没有搜索方法,它是为字符串搜索的。尝试$.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)

演示:Fiddle

由于您试图检查对象值中是否包含字符串,假设该字符串未用作任何键值,请尝试以下操作:

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

希望这有帮助:)