要在对象数组中搜索字符串

Want to search string in the array of objects?

本文关键字:搜索 字符串 数组 对象      更新时间:2023-09-26

我想搜索这个由对象组成的员工数组,我应该能够搜索任何文本,比如如果我传递-> search_for_string_in_array ('aaron', employees);它应该显示我'值存在于数组',或者如果它的方式请帮助我…

//here is the employeee  array ...
  var employees =[{
                          name:"jacob",
                          age :23,
                          city:"virginia",
                          yoe :12,
                          image :'a.jpg'
                       },
                       {
                          name:"aaron",
                          age :21,
                          city:"virginia",
                          yoe :12,
                          image :'b.jpg'
                       },
                       {
                          name:"johnny",
                          age :50,
                          city:"texas",
                          yoe :12,
                          image :'c.jpg'
                       },
                       {
                          name:"jacob",
                          age :12,
                          city:"virginia",
                          yoe :12,
                          image :'a.jpg'
                       }];

是在数组中执行搜索功能的函数。

    function search_for_string_in_array(search_for_string, employees) 
            {
                for (var i=0; i < employees.length; i++) 
                {
                    if (employees[i].match(search_for_string))
                    { 
                        return 'Value exists in array';
                    }
                }
               return 'Value does NOT exist in array';
            }

只需将要搜索的值和数组传递给函数,它就会告诉你字符串是否作为数组值的一部分存在。

如果您知道数组的结构,您可能应该只遍历它并测试每个值。如果你不知道它的结构,你可以将数组字符串化为JSON,并对其进行正则表达式(尽管它不会那么安全):

function search_for_string_in_array(str, arr) {
    var json = JSON.stringify(arr);
    return new RegExp(':'"'+str+''"','g').test(json);
}

直接替换

if (employees[i].match(search_for_string))
与这个:

if (employees[i].name.match(search_for_string))

Try

function search(text) {
    text += '';
    var i, obj;
    var array = [];
    for (i = 0; i < employees.length; i++) {
        var obj = employees[i];
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (('' + obj[key]).indexOf(text) >= 0
                        || ('' + key).indexOf(text) >= 0) {
                    array.push(obj);
                    break;
                }
            }
        }
    }
    return array.length > 0;
}

Demo: Fiddle1 Fiddle2